rusty_pdf_core 0.2.1

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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! Lexing and parsing of PDF objects.
//!
//! The parser is tolerant where real files are sloppy (odd whitespace, stray
//! signs, bad `/Length`, unterminated containers at end of data) and bounded
//! where hostile files push: container nesting is counted, never recursed on
//! blindly, and nothing is allocated from a number in the file.

use crate::error::{syntax, Error, Result};
use crate::object::{Blob, Dictionary, Object, ObjectId, Stream, StringFormat};
use std::sync::Arc;

const WHITESPACE: u8 = 1;
const DELIMITER: u8 = 2;

/// The lexical class of every byte: one load where the lexer's hottest
/// loops (`skip_ws`, `token`) otherwise test two sets per byte.
static CLASS: [u8; 256] = {
    let mut t = [0u8; 256];
    // White space (ISO 32000-1, table 1).
    let ws = [0u8, 9, 10, 12, 13, 32];
    let mut i = 0;
    while i < ws.len() {
        t[ws[i] as usize] = WHITESPACE;
        i += 1;
    }
    // Delimiters (table 2).
    let delims = *b"()<>[]{}/%";
    let mut i = 0;
    while i < delims.len() {
        t[delims[i] as usize] = DELIMITER;
        i += 1;
    }
    t
};

/// PDF white-space characters (ISO 32000-1, table 1).
#[inline]
pub(crate) fn is_whitespace(b: u8) -> bool {
    CLASS[usize::from(b)] == WHITESPACE
}

#[inline]
pub(crate) fn is_regular(b: u8) -> bool {
    CLASS[usize::from(b)] == 0
}

/// First position of `needle` in `hay` at or after `from`.
pub(crate) fn find(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
    let first = *needle.first()?;
    let mut at = from;
    while at + needle.len() <= hay.len() {
        let step = hay[at..=hay.len() - needle.len()].iter().position(|b| *b == first)?;
        at += step;
        if hay[at..].starts_with(needle) {
            return Some(at);
        }
        at += 1;
    }
    None
}

/// Last position of `needle` in `hay` that starts before `before`.
pub(crate) fn rfind(hay: &[u8], needle: &[u8], before: usize) -> Option<usize> {
    if needle.is_empty() || hay.len() < needle.len() {
        return None;
    }
    let mut at = before.min(hay.len() - needle.len() + 1);
    while at > 0 {
        at -= 1;
        if hay[at..].starts_with(needle) {
            return Some(at);
        }
    }
    None
}

/// Interpret a token as a number, if it is one.
///
/// Accepts what writers produce in practice: a leading `+` or `-` (or
/// several), `.5`, `5.`, and nothing else. No exponents: PDF has none, and
/// `1e5` in a content stream is an operator-shaped token, not a number.
/// (The parser reads numbers through [`parse_number_prefix`]; this whole-token
/// form is what the oracle test holds it to.)
#[cfg(test)]
fn parse_number(tok: &[u8]) -> Option<Object> {
    match parse_number_prefix(tok) {
        Some((n, len)) if len == tok.len() => Some(n),
        _ => None,
    }
}

/// The longest number-shaped prefix of `bytes` — signs, then digits with at
/// most one dot — as a number, with the bytes it used; `None` without a
/// digit. One pass: validate, accumulate the digits, and count the digits
/// after the dot, where a token scan and a second parse used to read every
/// number twice.
pub(crate) fn parse_number_prefix(bytes: &[u8]) -> Option<(Object, usize)> {
    let mut i = 0;
    let mut negative = false;
    while let Some(b @ (b'+' | b'-')) = bytes.get(i) {
        negative ^= *b == b'-';
        i += 1;
    }
    let body_start = i;
    let mut mantissa: u64 = 0;
    let mut overflow = false;
    let mut digits = 0usize;
    let mut fraction_digits = 0usize;
    let mut dot = false;
    while let Some(&b) = bytes.get(i) {
        match b {
            b'0'..=b'9' => {
                digits += 1;
                if dot {
                    fraction_digits += 1;
                }
                match mantissa.checked_mul(10).and_then(|m| m.checked_add(u64::from(b - b'0'))) {
                    Some(m) => mantissa = m,
                    None => overflow = true,
                }
            }
            b'.' if !dot => dot = true,
            _ => break,
        }
        i += 1;
    }
    if digits == 0 {
        return None;
    }
    if !dot && !overflow {
        if let Ok(v) = i64::try_from(mantissa) {
            return Some((Object::Integer(if negative { -v } else { v }), i));
        }
    }
    // Exact fast path: a mantissa below 2^53 and 10^k for k <= 22 are both
    // exactly representable, so the IEEE division is correctly rounded —
    // the same value `str::parse::<f64>` returns.
    if !overflow && mantissa < (1 << 53) && fraction_digits < POW10.len() {
        // Below 2^53: the conversion is exact.
        #[allow(clippy::cast_precision_loss)]
        let v = mantissa as f64 / POW10[fraction_digits];
        return Some((Object::Real(if negative { -v } else { v }), i));
    }
    // ASCII digits with at most one dot: valid UTF-8, and a grammar the
    // standard parser accepts.
    let v = std::str::from_utf8(&bytes[body_start..i]).ok()?.parse::<f64>().ok()?;
    Some((Object::Real(if negative { -v } else { v }), i))
}

/// 10^0 to 10^22: every power of ten that an f64 holds exactly.
const POW10: [f64; 23] = [
    1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
    1e20, 1e21, 1e22,
];

const fn hex_value(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// A cursor over PDF syntax.
pub(crate) struct Parser<'a> {
    pub(crate) data: &'a [u8],
    pub(crate) pos: usize,
    max_depth: usize,
    /// Whether `N G R` is read as a reference (objects) or as two numbers and
    /// an operator (content streams).
    references: bool,
}

impl<'a> Parser<'a> {
    pub(crate) const fn new(data: &'a [u8], pos: usize, max_depth: usize) -> Self {
        Self { data, pos, max_depth, references: true }
    }

    /// A parser for content streams: no indirect references.
    pub(crate) const fn for_content(data: &'a [u8], max_depth: usize) -> Self {
        Self { data, pos: 0, max_depth, references: false }
    }

    pub(crate) fn peek(&self) -> Option<u8> {
        self.data.get(self.pos).copied()
    }

    pub(crate) fn peek_at(&self, ahead: usize) -> Option<u8> {
        self.data.get(self.pos.checked_add(ahead)?).copied()
    }

    pub(crate) const fn at_end(&self) -> bool {
        self.pos >= self.data.len()
    }

    /// Skip white space and comments.
    pub(crate) fn skip_ws(&mut self) {
        while let Some(b) = self.peek() {
            if is_whitespace(b) {
                self.pos += 1;
            } else if b == b'%' {
                while let Some(c) = self.peek() {
                    if c == b'\n' || c == b'\r' {
                        break;
                    }
                    self.pos += 1;
                }
            } else {
                break;
            }
        }
    }

    /// The run of regular characters at the cursor (possibly empty).
    pub(crate) fn token(&mut self) -> &'a [u8] {
        let start = self.pos;
        while self.peek().is_some_and(is_regular) {
            self.pos += 1;
        }
        &self.data[start..self.pos]
    }

    /// Consume `word` if it is the next token, exactly.
    pub(crate) fn eat_keyword(&mut self, word: &[u8]) -> bool {
        let rest = &self.data[self.pos.min(self.data.len())..];
        if rest.starts_with(word) && !rest.get(word.len()).copied().is_some_and(is_regular) {
            self.pos += word.len();
            true
        } else {
            false
        }
    }

    /// An unsigned integer token, for object headers and xref tables.
    pub(crate) fn unsigned(&mut self) -> Option<u64> {
        let start = self.pos;
        let mut v: u64 = 0;
        while let Some(b @ b'0'..=b'9') = self.peek() {
            v = v.checked_mul(10)?.checked_add(u64::from(b - b'0'))?;
            self.pos += 1;
        }
        (self.pos > start).then_some(v)
    }

    /// Parse one object.
    pub(crate) fn object(&mut self) -> Result<Object> {
        self.value(0)
    }

    fn value(&mut self, depth: usize) -> Result<Object> {
        self.skip_ws();
        let start = self.pos;
        let Some(b) = self.peek() else {
            return syntax(start, "unexpected end of data");
        };
        match b {
            b'/' => {
                self.pos += 1;
                Ok(Object::Name(self.name_body()))
            }
            b'(' => {
                self.pos += 1;
                Ok(Object::String(self.literal_string(), StringFormat::Literal))
            }
            b'<' if self.peek_at(1) == Some(b'<') => {
                self.pos += 2;
                self.dictionary(depth).map(Object::Dictionary)
            }
            b'<' => {
                self.pos += 1;
                Ok(Object::String(self.hex_string(), StringFormat::Hex))
            }
            b'[' => {
                self.pos += 1;
                self.array(depth).map(Object::Array)
            }
            b']' | b'>' | b')' | b'{' | b'}' => syntax(start, "unexpected delimiter"),
            _ => {
                // A number ends where a number can no longer continue, as in
                // pdf.js's lexer — also when it runs into the next token with
                // no space (`20184endobj`).
                if let Some((n, len)) = parse_number_prefix(&self.data[start..]) {
                    self.pos = start + len;
                    if self.references {
                        if let Object::Integer(num) = n {
                            if let Some(id) = self.reference_tail(num) {
                                return Ok(Object::Reference(id));
                            }
                        }
                    }
                    return Ok(n);
                }
                match self.token() {
                    b"true" => Ok(Object::Boolean(true)),
                    b"false" => Ok(Object::Boolean(false)),
                    b"null" => Ok(Object::Null),
                    _ => {
                        self.pos = start;
                        syntax(start, "not an object")
                    }
                }
            }
        }
    }

    /// After an integer: if ` G R` follows, consume it and return the id.
    fn reference_tail(&mut self, num: i64) -> Option<ObjectId> {
        let num = u32::try_from(num).ok()?;
        let save = self.pos;
        let id = (|| {
            self.skip_ws();
            let generation = u16::try_from(self.unsigned()?).ok()?;
            self.skip_ws();
            self.eat_keyword(b"R").then_some((num, generation))
        })();
        if id.is_none() {
            self.pos = save;
        }
        id
    }

    /// A name's bytes; the `/` is already consumed.
    fn name_body(&mut self) -> Vec<u8> {
        let raw = self.token();
        if !raw.contains(&b'#') {
            return raw.to_vec();
        }
        let mut out = Vec::with_capacity(raw.len());
        let mut i = 0;
        while i < raw.len() {
            if raw[i] == b'#' {
                if let (Some(h), Some(l)) = (
                    raw.get(i + 1).copied().and_then(hex_value),
                    raw.get(i + 2).copied().and_then(hex_value),
                ) {
                    out.push(h << 4 | l);
                    i += 3;
                    continue;
                }
            }
            out.push(raw[i]);
            i += 1;
        }
        out
    }

    /// A literal string's bytes; the `(` is already consumed. An unterminated
    /// string ends at the end of the data.
    fn literal_string(&mut self) -> Vec<u8> {
        let mut out = Vec::new();
        let mut depth = 1usize;
        loop {
            // Copy the run of plain bytes up to the next byte that needs
            // attention, in one slice instead of one push per byte.
            let rest = self.data.get(self.pos..).unwrap_or(&[]);
            let run = rest.iter().position(|b| matches!(b, b'(' | b')' | b'\\' | b'\r')).unwrap_or(rest.len());
            out.extend_from_slice(&rest[..run]);
            self.pos += run;
            let Some(b) = self.peek() else { break };
            self.pos += 1;
            match b {
                b'(' => {
                    depth += 1;
                    out.push(b);
                }
                b')' => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                    out.push(b);
                }
                b'\\' => {
                    let Some(e) = self.peek() else { break };
                    self.pos += 1;
                    match e {
                        b'n' => out.push(b'\n'),
                        b'r' => out.push(b'\r'),
                        b't' => out.push(b'\t'),
                        b'b' => out.push(8),
                        b'f' => out.push(12),
                        b'0'..=b'7' => {
                            let mut v = u32::from(e - b'0');
                            for _ in 0..2 {
                                match self.peek() {
                                    Some(d @ b'0'..=b'7') => {
                                        v = v * 8 + u32::from(d - b'0');
                                        self.pos += 1;
                                    }
                                    _ => break,
                                }
                            }
                            // High-order overflow is ignored (7.3.4.2).
                            out.push((v & 0xFF) as u8);
                        }
                        // A backslash before an end-of-line continues the line.
                        b'\r' => {
                            if self.peek() == Some(b'\n') {
                                self.pos += 1;
                            }
                        }
                        b'\n' => {}
                        other => out.push(other),
                    }
                }
                // An end-of-line inside a string is one LF, however written.
                b'\r' => {
                    if self.peek() == Some(b'\n') {
                        self.pos += 1;
                    }
                    out.push(b'\n');
                }
                _ => out.push(b),
            }
        }
        out
    }

    /// A hex string's bytes; the `<` is already consumed.
    fn hex_string(&mut self) -> Vec<u8> {
        let mut out = Vec::new();
        let mut high: Option<u8> = None;
        while let Some(b) = self.peek() {
            self.pos += 1;
            if b == b'>' {
                break;
            }
            if let Some(v) = hex_value(b) {
                match high.take() {
                    Some(h) => out.push(h << 4 | v),
                    None => high = Some(v),
                }
            }
        }
        if let Some(h) = high {
            out.push(h << 4);
        }
        out
    }

    fn enter(&self, depth: usize) -> Result<usize> {
        if depth >= self.max_depth {
            return Err(Error::Limit { what: "container nesting", limit: self.max_depth as u64 });
        }
        Ok(depth + 1)
    }

    /// An array's items; the `[` is already consumed.
    fn array(&mut self, depth: usize) -> Result<Vec<Object>> {
        let depth = self.enter(depth)?;
        let mut items = Vec::new();
        loop {
            self.skip_ws();
            match self.peek() {
                None => break,
                Some(b']') => {
                    self.pos += 1;
                    break;
                }
                // A container closed by the wrong bracket, or an object that
                // ends inside it: stop here and let the caller see the token.
                Some(b'>') => break,
                _ => {}
            }
            let before = self.pos;
            match self.value(depth) {
                Ok(o) => items.push(o),
                Err(e @ Error::Limit { .. }) => return Err(e),
                Err(_) => {
                    // An unknown keyword inside an array: `endobj` and
                    // friends end the array, anything else is skipped.
                    self.pos = before;
                    let tok = self.token();
                    if tok.is_empty() {
                        self.pos += 1;
                    } else if matches!(tok, b"endobj" | b"endstream" | b"stream" | b"obj") {
                        self.pos = before;
                        break;
                    }
                }
            }
        }
        Ok(items)
    }

    /// A dictionary's entries; the `<<` is already consumed.
    fn dictionary(&mut self, depth: usize) -> Result<Dictionary> {
        let depth = self.enter(depth)?;
        let mut dict = Dictionary::new();
        loop {
            self.skip_ws();
            match self.peek() {
                None => break,
                Some(b'>') => {
                    self.pos += if self.peek_at(1) == Some(b'>') { 2 } else { 1 };
                    break;
                }
                Some(b'/') => {
                    self.pos += 1;
                    let key = self.name_body();
                    self.skip_ws();
                    // `/Key >>`: a key with no value is a null entry.
                    if self.peek() == Some(b'>') {
                        continue;
                    }
                    let before = self.pos;
                    match self.value(depth) {
                        Ok(v) => dict.set(key, v),
                        Err(e @ Error::Limit { .. }) => return Err(e),
                        Err(_) => {
                            self.pos = before;
                            let tok = self.token();
                            if tok.is_empty() {
                                self.pos += 1;
                            } else if matches!(tok, b"endobj" | b"endstream" | b"stream" | b"obj") {
                                self.pos = before;
                                break;
                            }
                        }
                    }
                }
                Some(_) => {
                    // Not a key. `endobj` and friends end the dictionary;
                    // any other junk token is skipped.
                    let before = self.pos;
                    let tok = self.token();
                    if tok.is_empty() {
                        self.pos += 1;
                    } else if matches!(tok, b"endobj" | b"endstream" | b"stream" | b"obj") {
                        self.pos = before;
                        break;
                    }
                }
            }
        }
        Ok(dict)
    }

    /// `N G obj`, leaving the cursor after `obj`.
    pub(crate) fn indirect_header(&mut self) -> Result<ObjectId> {
        self.skip_ws();
        let start = self.pos;
        let id = (|| {
            let num = u32::try_from(self.unsigned()?).ok()?;
            self.skip_ws();
            let generation = u16::try_from(self.unsigned()?).ok()?;
            self.skip_ws();
            self.eat_keyword(b"obj").then_some((num, generation))
        })();
        match id {
            Some(id) => Ok(id),
            None => {
                self.pos = start;
                syntax(start, "expected an object header")
            }
        }
    }

    /// A whole indirect object at the cursor: header, value, and stream data
    /// if there is any.
    ///
    /// `source` must be the buffer this parser reads (stream data is shared
    /// with it, not copied). `length_of` turns the `/Length` entry into a byte
    /// count; it is where an indirect length gets resolved.
    pub(crate) fn indirect_object(
        &mut self,
        source: &Arc<[u8]>,
        length_of: &mut dyn FnMut(&Object) -> Option<usize>,
    ) -> Result<(ObjectId, Object)> {
        let id = self.indirect_header()?;
        self.skip_ws();
        // `N G obj endobj` is a null object.
        if self.data[self.pos.min(self.data.len())..].starts_with(b"endobj") {
            self.pos += 6;
            return Ok((id, Object::Null));
        }
        let value = self.object()?;
        self.skip_ws();
        let value = match value {
            Object::Dictionary(dict) if self.eat_keyword(b"stream") => {
                let range = self.stream_data(&dict, length_of);
                Object::Stream(Stream::from_blob(dict, Blob::window(source, range)))
            }
            other => other,
        };
        self.skip_ws();
        self.eat_keyword(b"endobj");
        Ok((id, value))
    }

    /// The byte range of a stream's data; `stream` is already consumed. The
    /// cursor is left after `endstream`.
    fn stream_data(
        &mut self,
        dict: &Dictionary,
        length_of: &mut dyn FnMut(&Object) -> Option<usize>,
    ) -> std::ops::Range<usize> {
        // The keyword is followed by CRLF or LF (7.3.8.1). A lone CR is not
        // allowed, and is tolerated.
        match (self.peek(), self.peek_at(1)) {
            (Some(b'\r'), Some(b'\n')) => self.pos += 2,
            (Some(b'\n' | b'\r'), _) => self.pos += 1,
            _ => {}
        }
        let start = self.pos.min(self.data.len());
        let declared = dict.get(b"Length").and_then(&mut *length_of);
        if let Some(end) = declared.and_then(|len| start.checked_add(len)) {
            if end <= self.data.len() {
                let mut probe = Parser::new(self.data, end, 0);
                probe.skip_ws();
                if probe.eat_keyword(b"endstream") {
                    self.pos = probe.pos;
                    return start..end;
                }
            }
        }
        // `/Length` is missing or wrong: the data runs to `endstream`.
        let (mut end, after) = match find(self.data, b"endstream", start) {
            Some(p) => (p, p + 9),
            None => match find(self.data, b"endobj", start) {
                Some(p) => (p, p),
                None => (self.data.len(), self.data.len()),
            },
        };
        // The end-of-line before `endstream` is not data.
        if end > start && self.data[end - 1] == b'\n' {
            end -= 1;
        }
        if end > start && self.data[end - 1] == b'\r' {
            end -= 1;
        }
        self.pos = after;
        start..end
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(s: &[u8]) -> Object {
        Parser::new(s, 0, 64).object().unwrap()
    }

    #[test]
    fn numbers() {
        assert_eq!(parse(b"42"), Object::Integer(42));
        assert_eq!(parse(b"-7"), Object::Integer(-7));
        assert_eq!(parse(b"+3"), Object::Integer(3));
        assert_eq!(parse(b"--3"), Object::Integer(3));
        assert_eq!(parse(b".5"), Object::Real(0.5));
        assert_eq!(parse(b"-.5"), Object::Real(-0.5));
        assert_eq!(parse(b"5."), Object::Real(5.0));
        assert_eq!(parse(b"99999999999999999999"), Object::Real(1e20));
        assert!(Parser::new(b"inf", 0, 64).object().is_err());
        assert!(Parser::new(b"-", 0, 64).object().is_err());
    }

    /// The fast paths against the standard library's parsers, which the
    /// previous implementation used for every number.
    #[test]
    fn numbers_match_the_standard_parsers() {
        let oracle = |tok: &str| -> Option<Object> {
            let body = tok.trim_start_matches(['+', '-']);
            let negative = tok[..tok.len() - body.len()].bytes().filter(|b| *b == b'-').count() % 2 == 1;
            if body.is_empty() || body.bytes().any(|b| !b.is_ascii_digit() && b != b'.') || body.matches('.').count() > 1 || !body.bytes().any(|b| b.is_ascii_digit()) {
                return None;
            }
            if !body.contains('.') {
                if let Ok(v) = body.parse::<i64>() {
                    return Some(Object::Integer(if negative { -v } else { v }));
                }
            }
            let v = body.parse::<f64>().ok()?;
            Some(Object::Real(if negative { -v } else { v }))
        };
        let mut cases: Vec<String> = [
            "0", "-0", "7", "+7", "--7", "-+-7", "007", "1.", ".1", "-.1", "0.5", "612.000", "3.14159", "123456.789",
            "0.1", "0.2", "0.3", "1e5", ".", "-.", "1..2", "9223372036854775807", "9223372036854775808",
            "-9223372036854775808", "18446744073709551615", "18446744073709551616", "9007199254740993",
            "9007199254740993.0", "0.0000000000000000000001", "0.00000000000000000000001", "1234567890123456.7",
            "99999999999999999999.5",
        ]
        .iter()
        .map(|s| (*s).to_owned())
        .collect();
        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        for _ in 0..20_000 {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            let int = state % 10_000_000_000;
            let frac_len = (state >> 40) % 25;
            let mut s = format!("{int}");
            if frac_len > 0 {
                let frac = format!("{:024}", state >> 20);
                s.push('.');
                s.push_str(&frac[..frac_len as usize]);
            }
            if state & 1 == 1 {
                s.insert(0, '-');
            }
            cases.push(s);
        }
        for c in &cases {
            let ours = parse_number(c.as_bytes());
            let theirs = oracle(c);
            match (&ours, &theirs) {
                (Some(Object::Real(a)), Some(Object::Real(b))) => assert_eq!(a.to_bits(), b.to_bits(), "{c}"),
                _ => assert_eq!(ours, theirs, "{c}"),
            }
        }
    }

    #[test]
    fn a_number_ends_where_a_number_cannot_continue() {
        let mut p = Parser::new(b"20184endobj", 0, 64);
        assert_eq!(p.object().unwrap(), Object::Integer(20184));
        assert!(p.eat_keyword(b"endobj"));
        // `1e5` is the number 1 and then the token `e5`, as pdf.js reads it.
        let mut p = Parser::new(b"1e5", 0, 64);
        assert_eq!(p.object().unwrap(), Object::Integer(1));
        assert_eq!(p.token(), b"e5");
        let mut p = Parser::for_content(b"0Tc", 64);
        assert_eq!(p.object().unwrap(), Object::Integer(0));
        assert_eq!(p.token(), b"Tc");
        // A reference whose `R` touches the generation still reads.
        assert_eq!(Parser::new(b"12 0R", 0, 64).object().unwrap(), Object::Reference((12, 0)));
    }

    #[test]
    fn names_and_strings() {
        assert_eq!(parse(b"/A#20B"), Object::name("A B"));
        assert_eq!(parse(b"/A#ZZ"), Object::name("A#ZZ"));
        assert_eq!(parse(b"/"), Object::name(""));
        assert_eq!(parse(b"(a(b)c)"), Object::string("a(b)c"));
        assert_eq!(parse(b"(a\\)\\101\\n\\\r\nb)"), Object::string("a)A\nb"));
        assert_eq!(parse(b"(a\r\nb\rc)"), Object::string("a\nb\nc"));
        assert_eq!(parse(b"(\\0053)"), Object::string("\u{5}3"));
        assert_eq!(parse(b"(unterminated"), Object::string("unterminated"));
        assert_eq!(parse(b"<48 65 6c6C 6f>"), Object::String(b"Hello".to_vec(), StringFormat::Hex));
        assert_eq!(parse(b"<4>"), Object::String(vec![0x40], StringFormat::Hex));
    }

    #[test]
    fn containers_and_references() {
        let o = parse(b"<< /Type /Page /Kids [1 0 R 2 0 R 3] /N 5 0 /X null >>");
        let d = o.as_dict().unwrap();
        assert_eq!(d.get_name(b"Type"), Some(&b"Page"[..]));
        assert_eq!(
            d.get(b"Kids").unwrap().as_array().unwrap(),
            &[Object::Reference((1, 0)), Object::Reference((2, 0)), Object::Integer(3)]
        );
        // `5 0` with no `R` is the integer 5; the stray `0` is skipped.
        assert_eq!(d.get_i64(b"N"), Some(5));
        assert_eq!(d.get(b"X"), Some(&Object::Null));
    }

    #[test]
    fn sloppy_containers_end_where_the_data_does() {
        assert_eq!(parse(b"[1 2"), Object::Array(vec![1.into(), 2.into()]));
        let d = parse(b"<< /A 1 /B >>");
        assert_eq!(d.as_dict().unwrap().len(), 1);
        let d = parse(b"<< /A 1 endobj");
        assert_eq!(d.as_dict().unwrap().get_i64(b"A"), Some(1));
        // Repeated key: the last value wins.
        let d = parse(b"<< /A 1 /A 2 >>");
        assert_eq!(d.as_dict().unwrap().get_i64(b"A"), Some(2));
    }

    #[test]
    fn nesting_is_bounded() {
        let deep = vec![b'['; 100_000];
        let e = Parser::new(&deep, 0, 64).object().unwrap_err();
        assert!(matches!(e, Error::Limit { .. }));
        let mut dicts = Vec::new();
        for _ in 0..100_000 {
            dicts.extend_from_slice(b"<</A");
        }
        let e = Parser::new(&dicts, 0, 64).object().unwrap_err();
        assert!(matches!(e, Error::Limit { .. }));
    }

    #[test]
    fn content_mode_has_no_references() {
        let mut p = Parser::for_content(b"1 0 R", 64);
        assert_eq!(p.object().unwrap(), Object::Integer(1));
        assert_eq!(p.object().unwrap(), Object::Integer(0));
    }

    fn indirect(src: &[u8]) -> (ObjectId, Object) {
        let source: Arc<[u8]> = src.into();
        let mut p = Parser::new(&source, 0, 64);
        p.indirect_object(&source, &mut |l| l.as_i64().ok().and_then(|v| usize::try_from(v).ok()))
            .unwrap()
    }

    #[test]
    fn streams() {
        let (id, o) = indirect(b"4 0 obj\n<< /Length 5 >>\nstream\nhello\nendstream\nendobj");
        assert_eq!(id, (4, 0));
        assert_eq!(o.as_stream().unwrap().raw(), b"hello");
        // Wrong length: the data runs to `endstream`.
        let (_, o) = indirect(b"4 0 obj << /Length 99 >> stream\r\nhello\r\nendstream endobj");
        assert_eq!(o.as_stream().unwrap().raw(), b"hello");
        // No length, no endstream.
        let (_, o) = indirect(b"4 0 obj << >> stream\nhello");
        assert_eq!(o.as_stream().unwrap().raw(), b"hello");
        let (_, o) = indirect(b"7 0 obj endobj");
        assert_eq!(o, Object::Null);
    }
}