Skip to main content

laminapdf_syntax/
parser.rs

1//! Object parser: turns tokens into [`Object`]s, including indirect objects and streams.
2
3use crate::diagnostic::Position;
4use crate::error::{Error, Result};
5use crate::lexer::{Lexer, Token, is_whitespace};
6use crate::limits::{Limit, Limits};
7use crate::object::{Dict, Name, ObjRef, Object, Stream};
8
9/// Parses a single direct object from `input` with the default [`Limits`]. Trailing
10/// white-space and comments are allowed; anything else after the object is an error.
11///
12/// # Errors
13/// Returns an error on malformed syntax, truncation, or a hard limit exceeded
14/// ([`Limits::max_nesting_depth`], [`Limits::max_string_length`]).
15///
16/// # Examples
17/// ```
18/// use laminapdf_syntax::{parse_object, Object};
19/// let obj = parse_object(b"<< /Kids [3 0 R] /Count 1 >>")?;
20/// assert_eq!(obj.as_dict().and_then(|d| d.get_int("Count")), Some(1));
21/// # Ok::<(), laminapdf_syntax::Error>(())
22/// ```
23///
24/// Added in 0.2.0.
25pub fn parse_object(input: &[u8]) -> Result<Object> {
26    parse_object_with(input, &Limits::default())
27}
28
29/// [`parse_object`] with explicit `limits`.
30///
31/// # Errors
32/// As [`parse_object`].
33///
34/// # Examples
35/// ```
36/// use laminapdf_syntax::{Error, Limit, Limits, parse_object_with};
37/// let shallow = Limits::default().with_max_nesting_depth(1);
38/// assert!(parse_object_with(b"[1]", &shallow).is_ok());
39/// assert!(matches!(
40///     parse_object_with(b"[[1]]", &shallow),
41///     Err(Error::LimitExceeded { limit: Limit::NestingDepth, .. })
42/// ));
43/// ```
44///
45/// Added in 0.2.0.
46pub fn parse_object_with(input: &[u8], limits: &Limits) -> Result<Object> {
47    let mut parser = Parser::new(input, 0).with_limits(limits);
48    let obj = parser.object()?;
49    match parser.lex.next_token()? {
50        Token::Eof => Ok(obj),
51        _ => Err(Error::Syntax {
52            at: Position::offset(parser.lex.pos()),
53            message: "trailing data after object",
54        }),
55    }
56}
57
58/// A parser over PDF bytes, positioned at a byte offset.
59///
60/// Used for single objects ([`Parser::object`]) and for the file-structure layer
61/// ([`Parser::object_header`], [`Parser::indirect_object`]).
62///
63/// Added in 0.2.0.
64#[derive(Debug, Clone)]
65pub struct Parser<'a> {
66    lex: Lexer<'a>,
67    max_nesting_depth: usize,
68    /// Whether a stream-extent check looked past the end of the input (the lexer tracks its
69    /// own reads; see [`Parser::reached_end`]).
70    reached_end: bool,
71    /// Whether a dictionary had something other than a name where a key belongs, which was
72    /// skipped ([`Parser::skipped_keys`]).
73    skipped_keys: bool,
74}
75
76/// The result of [`Parser::indirect_object`].
77///
78/// Added in 0.2.0.
79#[derive(Debug, Clone, PartialEq)]
80#[non_exhaustive]
81pub struct IndirectObject {
82    /// The object's number and generation, from its `num gen obj` header.
83    pub id: ObjRef,
84    /// The object's value (a [`Object::Stream`] for streams).
85    pub object: Object,
86    /// True when the object is a stream whose `/Length` was missing, wrong or unresolvable,
87    /// so its extent was recovered by scanning for `endstream`.
88    pub length_recovered: bool,
89    /// True when a dictionary in the object had something other than a name where a key
90    /// belongs, and it was skipped ([`Parser::skipped_keys`]).
91    pub skipped_keys: bool,
92}
93
94/// What [`Parser::indirect_head`] read.
95///
96/// Added in 0.2.0.
97#[derive(Debug, Clone, PartialEq)]
98pub enum IndirectHead {
99    /// An object that is not a stream: complete.
100    Object(IndirectObject),
101    /// A stream whose extent is still to be found.
102    Stream(StreamHead),
103}
104
105/// A stream's header and dictionary, before its data is read ([`Parser::indirect_head`]).
106///
107/// Added in 0.2.0.
108#[derive(Debug, Clone, PartialEq)]
109#[non_exhaustive]
110pub struct StreamHead {
111    /// The object's number and generation.
112    pub id: ObjRef,
113    /// The stream dictionary.
114    pub dict: Dict,
115    /// Offset of the first data byte (after `stream` and its EOL).
116    pub data_start: usize,
117    /// `/Length` as declared (resolved when indirect); `None` when missing or unresolvable.
118    pub declared_length: Option<i64>,
119    /// True when the stream dictionary had something other than a name where a key belongs,
120    /// and it was skipped ([`Parser::skipped_keys`]).
121    pub skipped_keys: bool,
122}
123
124impl StreamHead {
125    /// Where the data ends if `/Length` is right (`None` when it is missing, negative or
126    /// overflows).
127    ///
128    /// Added in 0.2.0.
129    #[must_use]
130    pub fn declared_end(&self) -> Option<usize> {
131        self.declared_length
132            .and_then(|len| usize::try_from(len).ok())
133            .and_then(|len| self.data_start.checked_add(len))
134    }
135
136    /// The finished object: this stream with `data`; `length_recovered` when the extent was
137    /// found by scanning for `endstream` rather than from `/Length`.
138    ///
139    /// Added in 0.2.0.
140    #[must_use]
141    pub fn into_object(self, data: Vec<u8>, length_recovered: bool) -> IndirectObject {
142        IndirectObject {
143            id: self.id,
144            object: Object::Stream(Stream { dict: self.dict, data }),
145            length_recovered,
146            skipped_keys: self.skipped_keys,
147        }
148    }
149}
150
151impl<'a> Parser<'a> {
152    /// A parser over `data`, starting at byte offset `pos`, with the default [`Limits`].
153    ///
154    /// Added in 0.2.0.
155    pub const fn new(data: &'a [u8], pos: usize) -> Self {
156        Self {
157            lex: Lexer::new(data, pos),
158            max_nesting_depth: Limits::new().max_nesting_depth(),
159            reached_end: false,
160            skipped_keys: false,
161        }
162    }
163
164    /// Applies `limits` ([`Limits::max_nesting_depth`] and [`Limits::max_string_length`]).
165    ///
166    /// Added in 0.2.0.
167    #[must_use]
168    pub const fn with_limits(mut self, limits: &Limits) -> Self {
169        self.lex = self.lex.with_limits(limits);
170        self.max_nesting_depth = limits.max_nesting_depth();
171        self
172    }
173
174    /// The current byte offset.
175    ///
176    /// Added in 0.2.0.
177    pub const fn pos(&self) -> usize {
178        self.lex.pos()
179    }
180
181    /// Whether parsing so far has looked for a byte past the end of the input: to finish a
182    /// token ([`Lexer::reached_end`]), or to find a stream's `endstream`.
183    ///
184    /// When it has not, the result (value or error) depends only on bytes before the end, so
185    /// parsing a window of a larger input gave the same result as parsing the whole input.
186    /// `laminapdf-cos` relies on this to read sources without an in-memory slice in windows.
187    ///
188    /// Added in 0.2.0.
189    pub const fn reached_end(&self) -> bool {
190        self.reached_end || self.lex.reached_end()
191    }
192
193    /// Whether a dictionary parsed so far by this parser, in any object, had something other
194    /// than a name where a key belongs; it is never reset. Such a token is skipped, as pdf.js
195    /// and PDFium do, and parsing goes on with the next one: a number, string or other keyword,
196    /// a whole array or dictionary (with a reference `n g R` as one), a stray `]`, or an
197    /// unbalanced `)` or `>`. An object keyword (`obj`, `endobj`, `stream`, `endstream`) still
198    /// ends the parse with an error: the dictionary was never closed. Callers report it
199    /// (ADR 0003 §1).
200    ///
201    /// Added in 0.4.0.
202    pub const fn skipped_keys(&self) -> bool {
203        self.skipped_keys
204    }
205
206    /// Parses one direct object (references resolved lexically as `n g R`).
207    ///
208    /// # Errors
209    /// Malformed syntax, truncation, or a hard limit exceeded ([`Limits::max_nesting_depth`],
210    /// [`Limits::max_string_length`]).
211    ///
212    /// Added in 0.2.0.
213    pub fn object(&mut self) -> Result<Object> {
214        let tok = self.lex.next_token()?;
215        self.object_from(tok, 0)
216    }
217
218    fn object_from(&mut self, tok: Token<'a>, depth: usize) -> Result<Object> {
219        let start = self.lex.pos();
220        match tok {
221            Token::Integer(i) => Ok(self.maybe_reference(i)),
222            Token::ArrayOpen => {
223                let depth = self.enter(depth, start)?;
224                let mut items = Vec::new();
225                loop {
226                    match self.lex.next_token()? {
227                        Token::ArrayClose => return Ok(Object::Array(items)),
228                        Token::Eof => {
229                            return Err(Error::UnexpectedEof {
230                                at: Position::offset(self.lex.pos()),
231                            });
232                        }
233                        t => items.push(self.object_from(t, depth)?),
234                    }
235                }
236            }
237            Token::DictOpen => {
238                let depth = self.enter(depth, start)?;
239                self.dictionary(depth).map(Object::Dict)
240            }
241            Token::Eof => Err(Error::UnexpectedEof {
242                at: Position::offset(start),
243            }),
244            scalar => scalar.into_scalar().ok_or(Error::Syntax {
245                at: Position::offset(start),
246                message: "unexpected token",
247            }),
248        }
249    }
250
251    /// The entries of a dictionary whose `<<` was just read, up to and including its `>>`.
252    /// Something other than a name where a key belongs is skipped ([`Parser::skipped_keys`]).
253    fn dictionary(&mut self, depth: usize) -> Result<Dict> {
254        let mut dict = Dict::new();
255        loop {
256            if self.skip_unbalanced_delimiter() {
257                continue;
258            }
259            let start = self.lex.pos();
260            match self.lex.next_token()? {
261                Token::DictClose => return Ok(dict),
262                Token::Name(key) => {
263                    let value_tok = self.lex.next_token()?;
264                    if value_tok == Token::DictClose {
265                        // `<< /Key >>`: tolerate a missing value as null and stop.
266                        dict.insert(Name(key), Object::Null);
267                        return Ok(dict);
268                    }
269                    let value = self.object_from(value_tok, depth)?;
270                    dict.insert(Name(key), value);
271                }
272                Token::Eof => {
273                    return Err(Error::UnexpectedEof {
274                        at: Position::offset(self.lex.pos()),
275                    });
276                }
277                Token::Keyword(b"obj" | b"endobj" | b"stream" | b"endstream") => {
278                    return Err(Error::Syntax {
279                        at: Position::offset(start),
280                        message: "dictionary key must be a name",
281                    });
282                }
283                Token::Keyword(_) | Token::ArrayClose => self.skipped_keys = true,
284                other => {
285                    self.object_from(other, depth)?;
286                    self.skipped_keys = true;
287                }
288            }
289        }
290    }
291
292    /// Skips an unbalanced `)` or a `>` that does not start `>>` where a dictionary key
293    /// belongs: the lexer rejects both, as neither can start a token.
294    fn skip_unbalanced_delimiter(&mut self) -> bool {
295        self.lex.skip_whitespace();
296        let pos = self.lex.pos();
297        let data = self.lex.data();
298        let unbalanced = match data.get(pos) {
299            Some(b')') => true,
300            Some(b'>') => {
301                // Whether it is `>>` depends on the next byte: past the end, the caller
302                // reading a window must retry with a larger one (`Parser::reached_end`).
303                self.reached_end |= pos + 1 >= data.len();
304                data.get(pos + 1) != Some(&b'>')
305            }
306            _ => false,
307        };
308        if unbalanced {
309            self.lex.set_pos(pos + 1);
310            self.skipped_keys = true;
311        }
312        unbalanced
313    }
314
315    /// After an integer, looks ahead for `gen R`; rewinds if it is not a reference. An
316    /// integer that can't be an object number is not followed by a look ahead at all, so its
317    /// result never depends on the bytes after it ([`Parser::reached_end`]).
318    fn maybe_reference(&mut self, num: i64) -> Object {
319        let save = self.lex.pos();
320        if let Ok(num_u32) = u32::try_from(num)
321            && let Ok(Token::Integer(g)) = self.lex.next_token()
322            && let Ok(gen_nr) = u16::try_from(g)
323            && let Ok(Token::Keyword(b"R")) = self.lex.next_token()
324        {
325            return Object::Ref(ObjRef::new(num_u32, gen_nr));
326        }
327        self.lex.set_pos(save);
328        Object::Integer(num)
329    }
330
331    /// Reads `num gen obj` at the current position.
332    ///
333    /// # Errors
334    /// [`Error::Syntax`] when the next tokens are not an object header.
335    ///
336    /// Added in 0.2.0.
337    pub fn object_header(&mut self) -> Result<ObjRef> {
338        let offset = self.lex.pos();
339        let bad = || Error::Syntax {
340            at: Position::offset(offset),
341            message: "expected `n g obj`",
342        };
343        let Token::Integer(num) = self.lex.next_token()? else {
344            return Err(bad());
345        };
346        let Token::Integer(g) = self.lex.next_token()? else {
347            return Err(bad());
348        };
349        let Token::Keyword(b"obj") = self.lex.next_token()? else {
350            return Err(bad());
351        };
352        let num = u32::try_from(num).map_err(|_| bad())?;
353        let gen_nr = u16::try_from(g).map_err(|_| bad())?;
354        Ok(ObjRef::new(num, gen_nr))
355    }
356
357    /// Parses `num gen obj <object> [stream…endstream] endobj` at the current position.
358    ///
359    /// `resolve_length` resolves an indirect `/Length`; when it fails or the length is
360    /// wrong, the stream extent is recovered by scanning for `endstream`.
361    ///
362    /// # Errors
363    /// A malformed header or object, or a stream without any `endstream`.
364    ///
365    /// Added in 0.2.0.
366    pub fn indirect_object(&mut self, resolve_length: &mut dyn FnMut(ObjRef) -> Option<i64>) -> Result<IndirectObject> {
367        let head = match self.indirect_head(resolve_length)? {
368            IndirectHead::Object(object) => return Ok(object),
369            IndirectHead::Stream(head) => head,
370        };
371        let data = self.lex.data();
372        let end_flag = &mut self.reached_end;
373        let declared_end = head.declared_end().filter(|&end| endstream_at(data, end, end_flag));
374        let length_recovered = declared_end.is_none();
375        let end = if let Some(end) = declared_end {
376            end
377        } else {
378            let Some(endstream) = find(data, b"endstream", head.data_start) else {
379                *end_flag = true;
380                return Err(Error::UnexpectedEof {
381                    at: Position::offset(data.len()),
382                });
383            };
384            stream_data_end(data, head.data_start, endstream)
385        };
386        let bytes = data.get(head.data_start..end).unwrap_or_default().to_vec();
387        // Position after `endstream` (there is one at or after `end`), then consume an
388        // optional `endobj`.
389        let after = find(data, b"endstream", end).map_or(data.len(), |p| p + b"endstream".len());
390        self.lex.set_pos(after);
391        Ok(head.into_object(bytes, length_recovered))
392    }
393
394    /// The first part of [`Parser::indirect_object`]: the header and the value, and for a
395    /// stream, its dictionary, where its data starts and its declared `/Length` (resolved
396    /// with `resolve_length` when indirect), without looking for its end.
397    ///
398    /// For callers that find a stream's extent themselves (`laminapdf-cos` reading a source in
399    /// windows checks a `/Length` with a small read at the declared end instead of reading
400    /// up to it). [`endstream_at`] and [`stream_data_end`] are the checks
401    /// [`Parser::indirect_object`] makes, so both give the same result.
402    ///
403    /// # Errors
404    /// A malformed header or object.
405    ///
406    /// Added in 0.2.0.
407    pub fn indirect_head(&mut self, resolve_length: &mut dyn FnMut(ObjRef) -> Option<i64>) -> Result<IndirectHead> {
408        let id = self.object_header()?;
409        let obj = self.object()?;
410        let after_obj = self.lex.pos();
411        let skipped_keys = self.skipped_keys;
412        let plain = |object| {
413            IndirectHead::Object(IndirectObject {
414                id,
415                object,
416                length_recovered: false,
417                skipped_keys,
418            })
419        };
420        let Object::Dict(dict) = obj else {
421            return Ok(plain(obj));
422        };
423        if !matches!(self.lex.next_token(), Ok(Token::Keyword(b"stream"))) {
424            self.lex.set_pos(after_obj);
425            return Ok(plain(Object::Dict(dict)));
426        }
427        let data_start = skip_stream_eol(self.lex.data(), self.lex.pos(), &mut self.reached_end);
428        let declared_length = match dict.get("Length") {
429            Some(Object::Integer(n)) => Some(*n),
430            Some(Object::Ref(r)) => resolve_length(*r),
431            _ => None,
432        };
433        Ok(IndirectHead::Stream(StreamHead {
434            id,
435            dict,
436            data_start,
437            declared_length,
438            skipped_keys,
439        }))
440    }
441
442    /// The lexer this parser reads tokens from, for callers that mix tokens and objects (an
443    /// xref table followed by its trailer). Reads through it count for
444    /// [`Parser::reached_end`].
445    ///
446    /// Added in 0.2.0.
447    pub const fn lexer(&mut self) -> &mut Lexer<'a> {
448        &mut self.lex
449    }
450
451    /// One level deeper than `depth`, or [`Error::LimitExceeded`] past
452    /// [`Limits::max_nesting_depth`].
453    fn enter(&self, depth: usize, offset: usize) -> Result<usize> {
454        if depth >= self.max_nesting_depth {
455            return Err(Error::limit(Limit::NestingDepth, Some(offset)));
456        }
457        Ok(depth + 1)
458    }
459}
460
461/// After the `stream` keyword: skip spaces/tabs some writers emit, then CRLF, LF or a lone CR.
462/// Sets `reached_end` when it had to look past the end of `data`.
463fn skip_stream_eol(data: &[u8], mut pos: usize, reached_end: &mut bool) -> usize {
464    while matches!(data.get(pos), Some(b' ' | b'\t')) {
465        pos += 1;
466    }
467    let (first, second) = (data.get(pos), data.get(pos + 1));
468    if first.is_none() || (first == Some(&b'\r') && second.is_none()) {
469        *reached_end = true;
470    }
471    match (first, second) {
472        (Some(b'\r'), Some(b'\n')) => pos + 2,
473        (Some(b'\r' | b'\n'), _) => pos + 1,
474        _ => pos,
475    }
476}
477
478/// Whether `endstream` follows `end` after optional white-space: the check that a stream's
479/// declared `/Length` is right. Sets `reached_end` when the answer depends on bytes past the
480/// end of `data`.
481///
482/// Added in 0.2.0.
483pub fn endstream_at(data: &[u8], end: usize, reached_end: &mut bool) -> bool {
484    let mut pos = end;
485    while data.get(pos).copied().is_some_and(is_whitespace) {
486        pos += 1;
487    }
488    let rest = data.get(pos..).unwrap_or_default();
489    if rest.len() < b"endstream".len() {
490        *reached_end = true;
491    }
492    rest.starts_with(b"endstream")
493}
494
495/// The end of stream data that starts at `from` when its `endstream` keyword is at `idx`: the
496/// EOL before the keyword (CRLF, LF or CR) is not data. Reads only `data[idx - 2..idx]`.
497///
498/// Added in 0.2.0.
499pub fn stream_data_end(data: &[u8], from: usize, idx: usize) -> usize {
500    let mut end = idx;
501    if end > from && data.get(end - 1) == Some(&b'\n') {
502        end -= 1;
503    }
504    if end > from && data.get(end - 1) == Some(&b'\r') {
505        end -= 1;
506    }
507    end
508}
509
510/// Finds the first occurrence of `needle` in `hay` at or after byte offset `from`, returning
511/// its offset. Used to recover stream extents (`endstream`) and, in `laminapdf-cos`, to locate
512/// file-structure keywords. `None` when `from` is past the end or `needle` is absent.
513///
514/// ```
515/// assert_eq!(laminapdf_syntax::find(b"stream\nabc\nendstream", b"endstream", 0), Some(11));
516/// assert_eq!(laminapdf_syntax::find(b"abc", b"b", 2), None);
517/// ```
518///
519/// Added in 0.2.0.
520pub fn find(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
521    let tail = hay.get(from..)?;
522    tail.windows(needle.len()).position(|w| w == needle).map(|p| p + from)
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    fn no_length(_: ObjRef) -> Option<i64> {
530        None
531    }
532
533    #[test]
534    fn parse_object_reads_reference_inside_array() {
535        assert_eq!(
536            parse_object(b"[1 0 R 2]"),
537            Ok(Object::Array(vec![Object::Ref(ObjRef::new(1, 0)), Object::Integer(2)]))
538        );
539    }
540
541    #[test]
542    fn parse_object_rewinds_when_integers_are_not_a_reference() {
543        assert_eq!(
544            parse_object(b"[1 2 3]"),
545            Ok(Object::Array(vec![1.into(), 2.into(), 3.into()]))
546        );
547    }
548
549    /// The dictionary `input` parses to and whether a key was skipped.
550    fn dict_and_skipped(input: &[u8]) -> (Result<Object>, bool) {
551        let mut parser = Parser::new(input, 0);
552        let obj = parser.object();
553        (obj, parser.skipped_keys())
554    }
555
556    fn ab() -> Object {
557        Object::Dict([("A", 1), ("B", 2)].into_iter().collect())
558    }
559
560    #[test]
561    fn a_well_formed_dictionary_skips_no_keys() {
562        assert_eq!(dict_and_skipped(b"<< /A 1 /B 2 >>"), (Ok(ab()), false));
563    }
564
565    #[test]
566    fn parse_object_skips_what_is_not_a_name_where_a_key_belongs() {
567        let inputs: [&[u8]; 7] = [
568            b"<< /A 1 Size 6 /B 2 >>",
569            b"<< /A 1 (x) <0f> /B 2 >>",
570            b"<< /A 1 3 0 R /B 2 >>",
571            b"<< /A 1 [/C 3] << /D 4 >> /B 2 >>",
572            b"<< /A 1 ] /B 2 >>",
573            b"<< /A 1 f08d> /B 2 >>",
574            b"<< /A 1 ) /B 2 >>",
575        ];
576        for input in inputs {
577            assert_eq!(
578                dict_and_skipped(input),
579                (Ok(ab()), true),
580                "{}",
581                String::from_utf8_lossy(input)
582            );
583        }
584    }
585
586    #[test]
587    fn an_object_keyword_where_a_key_belongs_still_fails() {
588        assert!(matches!(
589            parse_object(b"<< /A 1 endobj"),
590            Err(Error::Syntax {
591                message: "dictionary key must be a name",
592                ..
593            })
594        ));
595    }
596
597    #[test]
598    fn a_close_angle_at_the_end_reaches_it() {
599        // `>` followed by the end may be the first half of `>>` in a larger window.
600        assert!(object_reached_end(b"<< /A 1 >"));
601    }
602
603    #[test]
604    fn indirect_object_reports_skipped_keys() {
605        let mut parser = Parser::new(b"5 0 obj << /A 1 Size 6 /B 2 >> endobj", 0);
606        assert!(parser.indirect_object(&mut no_length).unwrap().skipped_keys);
607    }
608
609    #[test]
610    fn a_stream_reports_skipped_keys_in_its_dictionary() {
611        let mut parser = Parser::new(b"5 0 obj << /Length 2 x >> stream\nab\nendstream endobj", 0);
612        assert!(parser.indirect_object(&mut no_length).unwrap().skipped_keys);
613    }
614
615    const MAX_DEPTH: usize = Limits::new().max_nesting_depth();
616
617    #[test]
618    fn parse_object_accepts_nesting_at_the_limit() {
619        let input = [vec![b'['; MAX_DEPTH], vec![b']'; MAX_DEPTH]].concat();
620        assert!(parse_object(&input).is_ok());
621    }
622
623    #[test]
624    fn parse_object_rejects_nesting_past_the_limit() {
625        let input = [vec![b'['; MAX_DEPTH + 1], vec![b']'; MAX_DEPTH + 1]].concat();
626        assert!(matches!(
627            parse_object(&input),
628            Err(Error::LimitExceeded {
629                limit: Limit::NestingDepth,
630                ..
631            })
632        ));
633    }
634
635    #[test]
636    fn parse_object_with_reports_the_offset_of_the_container_past_the_limit() {
637        let limits = Limits::default().with_max_nesting_depth(2);
638        assert_eq!(
639            parse_object_with(b"[[ [1] ]]", &limits),
640            Err(Error::LimitExceeded {
641                limit: Limit::NestingDepth,
642                at: Some(Position::FileOffset(4))
643            })
644        );
645    }
646
647    #[test]
648    fn indirect_stream_with_correct_length_is_not_recovered() {
649        let input = b"4 0 obj << /Length 3 >> stream\nabc\nendstream endobj";
650        let parsed = Parser::new(input, 0).indirect_object(&mut no_length).unwrap();
651        assert!(!parsed.length_recovered);
652    }
653
654    #[test]
655    fn parse_object_rejects_trailing_garbage() {
656        assert!(parse_object(b"1 2").is_err());
657    }
658
659    #[test]
660    fn indirect_stream_with_wrong_length_recovers_by_scanning() {
661        let input = b"4 0 obj << /Length 999 >> stream\r\nabc\r\nendstream endobj";
662        let parsed = Parser::new(input, 0).indirect_object(&mut no_length).unwrap();
663        assert_eq!(
664            (parsed.object, parsed.length_recovered),
665            (
666                Object::Stream(Stream::new([("Length", 999)].into_iter().collect(), b"abc".to_vec())),
667                true
668            )
669        );
670    }
671
672    #[test]
673    fn indirect_stream_uses_resolved_indirect_length() {
674        let input = b"4 0 obj << /Length 5 0 R >> stream\nab\nendstream\n x endstream endobj";
675        let mut resolve = |_| Some(15);
676        let parsed = Parser::new(input, 0).indirect_object(&mut resolve).unwrap();
677        assert_eq!(parsed.object.as_ref_stream_data(), Some(&b"ab\nendstream\n x"[..]));
678    }
679
680    impl Object {
681        fn as_ref_stream_data(&self) -> Option<&[u8]> {
682            match self {
683                Self::Stream(s) => Some(&s.data),
684                _ => None,
685            }
686        }
687    }
688
689    fn reached_end(input: &[u8]) -> bool {
690        let mut parser = Parser::new(input, 0);
691        let _ = parser.indirect_object(&mut no_length);
692        parser.reached_end()
693    }
694
695    #[test]
696    fn a_complete_object_followed_by_more_input_does_not_reach_the_end() {
697        assert!(!reached_end(b"1 0 obj << /A 1 >> endobj\n2 0 obj"));
698    }
699
700    #[test]
701    fn a_dictionary_at_the_end_reaches_it_looking_for_stream() {
702        assert!(reached_end(b"1 0 obj << /A 1 >>"));
703    }
704
705    #[test]
706    fn a_stream_whose_length_runs_past_the_end_reaches_it() {
707        // The declared extent can't be checked, and the `endstream` scan finds none.
708        assert!(reached_end(b"1 0 obj << /Length 100 >> stream\nabc"));
709    }
710
711    #[test]
712    fn a_stream_with_a_valid_length_does_not_reach_the_end() {
713        assert!(!reached_end(b"1 0 obj << /Length 3 >> stream\nabc\nendstream endobj "));
714    }
715
716    #[test]
717    fn a_stream_without_endstream_after_its_length_reaches_the_end() {
718        // A wrong `/Length` makes the parser scan for `endstream`; a short window might hold
719        // only an `endstream` that sits inside the real data.
720        assert!(reached_end(b"1 0 obj << /Length 1 >> stream\nabc"));
721    }
722
723    fn object_reached_end(input: &[u8]) -> bool {
724        let mut parser = Parser::new(input, 0);
725        let _ = parser.object();
726        parser.reached_end()
727    }
728
729    #[test]
730    fn a_negative_integer_at_the_end_does_not_look_ahead_for_a_reference() {
731        // `-5` can't be an object number, so nothing after it can change the result.
732        assert!(!object_reached_end(b"-5 "));
733    }
734
735    #[test]
736    fn an_integer_pair_at_the_end_reaches_it_as_it_may_be_a_reference() {
737        // `5 0` might continue as `5 0 R`: the result depends on what follows.
738        assert!(object_reached_end(b"5 0"));
739    }
740
741    #[test]
742    fn indirect_head_stops_at_the_stream_data() {
743        let mut parser = Parser::new(b"1 0 obj << /Length 3 >> stream\nabc\nendstream", 0);
744        let Ok(IndirectHead::Stream(head)) = parser.indirect_head(&mut no_length) else {
745            panic!("not a stream head");
746        };
747        assert_eq!((head.data_start, head.declared_end()), (31, Some(34)));
748    }
749
750    #[test]
751    fn stream_data_end_drops_the_eol_before_endstream() {
752        assert_eq!(stream_data_end(b"abc\r\nendstream", 0, 5), 3);
753    }
754}