Skip to main content

structured_asn1/
reader.rs

1//! Reading elements in sequence, and descending into the constructed ones.
2//!
3//! Three invariants hold throughout. Nothing copies the document: elements
4//! borrow it and carry the range they occupy. Nothing recurses: depth is
5//! bounded by the caller's budget rather than by the stack. An element carries
6//! no path; the path belongs to the reader that produced it.
7
8use crate::error::{Error, ErrorCode, Limit, Path, Result};
9use crate::length::{self, Encoding, Length};
10use crate::limits::{Budget, Limits};
11use crate::memory::Memory;
12use crate::tag::{self, Tag, universal};
13use crate::value::{self, BitString, Integer, Oid};
14
15mod integer;
16pub use integer::IntegerReading;
17
18/// Holds the budget for one parse and hands out readers that share it.
19#[derive(Debug)]
20pub struct Parser {
21    budget: Budget,
22    encoding: Encoding,
23}
24
25impl Parser {
26    /// A parser for one document, in one encoding, with one budget.
27    #[must_use]
28    pub fn new(encoding: Encoding, limits: Limits, memory: Memory) -> Self {
29        Self {
30            budget: Budget::new(limits, memory),
31            encoding,
32        }
33    }
34
35    /// A parser for DER, with the default budget.
36    #[must_use]
37    pub fn der(memory: Memory) -> Self {
38        Self::new(Encoding::Der, Limits::default(), memory)
39    }
40
41    /// A parser that also accepts the BER forms CMS permits.
42    #[must_use]
43    pub fn ber(memory: Memory) -> Self {
44        Self::new(Encoding::Ber, Limits::default(), memory)
45    }
46
47    /// The limits this parser was given.
48    #[must_use]
49    pub fn limits(&self) -> Limits {
50        self.budget.limits()
51    }
52
53    /// The aggregate account shared with other parsers and retained results.
54    ///
55    /// `Limits.max_work` additionally bounds this parser's scanning, not later
56    /// owned-result processing. Memory's cumulative work bounds the whole domain.
57    #[must_use]
58    pub fn memory(&self) -> &Memory {
59        self.budget.memory()
60    }
61
62    /// A reader over `data`, whose first byte sits at `base` in the document.
63    ///
64    /// `base` is what makes an error's offset and an element's span mean
65    /// something to a caller holding a whole document while handing this parser
66    /// a window into it.
67    ///
68    /// Refused when the end of `data` would not fit an offset. Checking that
69    /// here is what lets every offset computed while reading be ordinary
70    /// arithmetic: each is at most `base + data.len()`.
71    pub fn read<'a>(&'a self, data: &'a [u8], base: u64) -> Result<Reader<'a>> {
72        self.read_as(data, base, self.encoding)
73    }
74
75    /// A reader over `data` under a chosen encoding, sharing this parser's
76    /// budget.
77    ///
78    /// For a window whose schema fixes its encoding regardless of what this
79    /// parser was built for: the value of a certificate extension is DER even
80    /// when the parser was made lenient for the envelope the certificate
81    /// arrived in.
82    pub fn read_as<'a>(
83        &'a self,
84        data: &'a [u8],
85        base: u64,
86        encoding: Encoding,
87    ) -> Result<Reader<'a>> {
88        self.read_as_in(data, base, encoding, self.memory())
89    }
90
91    fn read_as_in<'a>(
92        &'a self,
93        data: &'a [u8],
94        base: u64,
95        encoding: Encoding,
96        execution: &Memory,
97    ) -> Result<Reader<'a>> {
98        u64::try_from(data.len())
99            .ok()
100            .and_then(|length| base.checked_add(length))
101            .ok_or_else(|| Error::new(ErrorCode::OffsetTooLarge, base, Path::default()))?;
102
103        Ok(Reader {
104            data,
105            pos: 0,
106            base,
107            depth: 0,
108            next_index: 0,
109            path: Path::default(),
110            encoding,
111            parser: self,
112            execution: execution.clone(),
113        })
114    }
115
116    /// A reader over bytes another element carries as its value, one level
117    /// below the reader that element was found in.
118    ///
119    /// For an encoding wrapped in a primitive, an octet string above all: a
120    /// certificate extension's value, a signed message's content. `outer` is
121    /// [`Reader::depth`] of the reader the carrying element came from. A
122    /// reader made with [`Parser::read_as`] would count the wrapped structure
123    /// from the top again, and a caller's depth ceiling would bound each
124    /// wrapping rather than the document.
125    ///
126    /// # Errors
127    ///
128    /// [`ErrorCode::LimitExceeded`] where the level is past the depth
129    /// ceiling, and what [`Parser::read_as`] refuses.
130    pub fn read_nested<'a>(
131        &'a self,
132        data: &'a [u8],
133        base: u64,
134        encoding: Encoding,
135        outer: u32,
136    ) -> Result<Reader<'a>> {
137        self.read_nested_in(data, base, encoding, outer, self.memory())
138    }
139
140    /// Nested lazy reader using the current execution domain from creation.
141    ///
142    /// Original offsets, depth and this parser session's cumulative ceilings
143    /// remain in force. New storage and deferred work use `execution`.
144    pub fn read_nested_in<'a>(
145        &'a self,
146        data: &'a [u8],
147        base: u64,
148        encoding: Encoding,
149        outer: u32,
150        execution: &Memory,
151    ) -> Result<Reader<'a>> {
152        let mut reader = self.read_as_in(data, base, encoding, execution)?;
153        let depth = outer.checked_add(1).ok_or_else(|| {
154            Error::new(
155                ErrorCode::LimitExceeded(Limit::Depth),
156                base,
157                Path::default(),
158            )
159        })?;
160        self.budget
161            .depth(depth)
162            .map_err(|limit| Error::new(ErrorCode::LimitExceeded(limit), base, Path::default()))?;
163        reader.depth = depth;
164        Ok(reader)
165    }
166}
167
168/// Where in a document one run of bytes sits.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub struct Span {
171    /// Offset of the first byte, counted in the whole document.
172    pub start: u64,
173    /// How many bytes.
174    pub length: u64,
175}
176
177impl Span {
178    /// The offset just past the last byte.
179    ///
180    /// Ordinary arithmetic: a span is only ever built by a reader, which
181    /// refuses a window whose end does not fit an offset, so `start + length`
182    /// has already been shown to fit.
183    #[must_use]
184    pub fn end(self) -> u64 {
185        self.start + self.length
186    }
187}
188
189/// One element, as it was found.
190#[derive(Debug, Clone, Copy)]
191pub struct Element<'a> {
192    tag: Tag,
193    contents: &'a [u8],
194    bytes: &'a [u8],
195    contents_span: Span,
196    whole: Span,
197    indefinite: bool,
198    index: u32,
199}
200
201impl<'a> Element<'a> {
202    /// What kind of element this is.
203    #[must_use]
204    pub fn tag(self) -> Tag {
205        self.tag
206    }
207
208    /// The contents, borrowed from the document.
209    ///
210    /// For an indefinite-length element this is everything up to but not
211    /// including the end-of-contents marker.
212    #[must_use]
213    pub fn contents(self) -> &'a [u8] {
214        self.contents
215    }
216
217    /// The whole element as it arrived, header included.
218    ///
219    /// What a signature is computed over wherever a schema says the signature
220    /// covers an element as encoded, and what identity is compared on wherever
221    /// a schema says two structures are the same one when their bytes are.
222    /// Handing these back rather than re-encoding what was understood is the
223    /// difference between checking a signature over the document somebody was
224    /// sent and checking it over this parser's opinion of that document.
225    #[must_use]
226    pub fn as_bytes(self) -> &'a [u8] {
227        self.bytes
228    }
229
230    /// Where the contents sit in the document.
231    #[must_use]
232    pub fn contents_span(self) -> Span {
233        self.contents_span
234    }
235
236    /// Where the whole element sits, header included.
237    ///
238    /// This is the range a signature is computed over wherever a schema says
239    /// the signature covers an element as encoded.
240    #[must_use]
241    pub fn span(self) -> Span {
242        self.whole
243    }
244
245    /// Whether the length was written in the indefinite form.
246    #[must_use]
247    pub fn is_indefinite(self) -> bool {
248        self.indefinite
249    }
250
251    /// Its position among the elements of the container it was read from.
252    #[must_use]
253    pub fn index(self) -> u32 {
254        self.index
255    }
256}
257
258/// Reads the elements of one container, in order.
259///
260/// Cloning one keeps where it is and how deep it sits, so a caller that has to
261/// come back to a container later can put the reader aside rather than start
262/// again from the document and count the nesting as one.
263#[derive(Debug)]
264pub struct Reader<'a> {
265    data: &'a [u8],
266    pos: usize,
267    base: u64,
268    depth: u32,
269    next_index: u32,
270    path: Path,
271    encoding: Encoding,
272    parser: &'a Parser,
273    execution: Memory,
274}
275
276impl<'a> Reader<'a> {
277    /// Current domain for deferred work, copies and new storage.
278    #[must_use]
279    pub fn memory(&self) -> &Memory {
280        &self.execution
281    }
282
283    /// Selects the domain for subsequent execution without moving existing
284    /// storage charges. Offsets, depth and parser-session cumulative limits
285    /// remain unchanged; a new domain does not reset that session ceiling.
286    #[must_use]
287    pub fn with_execution(mut self, execution: &Memory) -> Self {
288        self.execution = execution.clone();
289        self
290    }
291
292    /// Copies the reader position and diagnostic path fallibly in the same domain.
293    pub fn try_clone(&self) -> Result<Self> {
294        Ok(Self {
295            data: self.data,
296            pos: self.pos,
297            base: self.base,
298            depth: self.depth,
299            next_index: self.next_index,
300            path: self
301                .path
302                .try_copy_in(self.memory())
303                .map_err(|reason| Error::resource(reason, self.offset()))?,
304            encoding: self.encoding,
305            parser: self.parser,
306            execution: self.execution.clone(),
307        })
308    }
309    /// Whether every element here has been read.
310    #[must_use]
311    pub fn is_empty(&self) -> bool {
312        self.pos >= self.data.len()
313    }
314
315    /// Original parser, whose session ceilings remain cumulative across
316    /// deferred reads. Use [`Self::memory`] for the current execution domain;
317    /// the parser's storage domain may belong to an earlier operation.
318    #[must_use]
319    pub fn parser(&self) -> &'a Parser {
320        self.parser
321    }
322
323    /// The shared budget, by way of the parser.
324    fn budget(&self) -> &'a Budget {
325        &self.parser.budget
326    }
327
328    /// Charges caller-side scanning to the shared work budget.
329    ///
330    /// For a schema layer that walks an element's contents itself, text
331    /// validation and named-bit walks among them: the walk costs what the
332    /// bytes cost, and a caller bounding work must see that cost on the
333    /// same meter the reads use.
334    pub fn charge(&self, amount: u64) -> Result<()> {
335        self.budget()
336            .work_in(amount, self.memory())
337            .map_err(|limit| self.fail_at(ErrorCode::LimitExceeded(limit), self.offset()))
338    }
339
340    /// How many containers deep this reader sits, counted as the depth
341    /// ceiling counts it. What [`Parser::read_nested`] is given for a value
342    /// found here.
343    #[must_use]
344    pub fn depth(&self) -> u32 {
345        self.depth
346    }
347
348    /// The offset of the next unread byte, in the document.
349    ///
350    /// Ordinary arithmetic, because `pos` never exceeds the length of `data`
351    /// and `base` plus that length was shown to fit when this reader was made.
352    #[must_use]
353    pub fn offset(&self) -> u64 {
354        self.base + self.pos as u64
355    }
356
357    /// The bytes not yet read.
358    #[must_use]
359    pub fn remaining(&self) -> &'a [u8] {
360        &self.data[self.pos.min(self.data.len())..]
361    }
362
363    /// The path to this container, for a caller building its own diagnostics.
364    #[must_use]
365    pub fn path(&self) -> &Path {
366        &self.path
367    }
368
369    /// Which encoding this reader accepts, for a schema whose own rules
370    /// differ between the two, such as the ordering DER requires of a set.
371    #[must_use]
372    pub fn encoding(&self) -> Encoding {
373        self.encoding
374    }
375
376    /// A reader over an element's own bytes, header included, under a chosen
377    /// encoding.
378    ///
379    /// For a structure whose schema fixes its encoding regardless of the
380    /// container's: a certificate is DER even when the envelope carrying it
381    /// is BER, and reading it with the container's leniency would let
382    /// spellings survive that the certificate's own rules refuse. The
383    /// element's header is read again under the chosen rules, so a header
384    /// only the lenient encoding accepts is refused too. Offsets stay offsets
385    /// in the document and the budget stays the shared one.
386    pub fn reread(&self, element: &Element<'a>, encoding: Encoding) -> Result<Reader<'a>> {
387        Ok(Reader {
388            data: element.bytes,
389            pos: 0,
390            base: element.whole.start,
391            depth: self.depth,
392            next_index: 0,
393            path: self
394                .path
395                .try_copy_in(self.memory())
396                .map_err(|reason| Error::resource(reason, element.whole.start))?,
397            encoding,
398            parser: self.parser,
399            execution: self.execution.clone(),
400        })
401    }
402
403    /// Reads the next element, or `None` at the end of this container.
404    pub fn next_element(&mut self) -> Result<Option<Element<'a>>> {
405        if self.is_empty() {
406            return Ok(None);
407        }
408
409        let header = self.read_header()?;
410
411        // An end-of-contents marker belongs to whichever reader opened the
412        // indefinite element, and that reader stops before handing it out.
413        // Meeting one here means it closes something never opened.
414        if header.tag.is_end_of_contents() {
415            return Err(self.fail_at(ErrorCode::MalformedEndOfContents, header.start));
416        }
417
418        self.finish(header).map(Some)
419    }
420
421    /// Reads the next element and requires it to carry `tag`.
422    pub fn expect(&mut self, tag: Tag) -> Result<Element<'a>> {
423        let offset = self.offset();
424        match self.next_element()? {
425            Some(element) if element.tag == tag => Ok(element),
426            // Named under the element that carried the wrong tag: it was read,
427            // so it has an index, and the fault is that element rather than
428            // the container holding it. Nothing was read in the other arm, so
429            // there is no element to name and the container is the answer.
430            Some(element) => Err(self.fail_under(ErrorCode::UnexpectedTag, &element)),
431            None => Err(self.fail_at(ErrorCode::UnexpectedEnd, offset)),
432        }
433    }
434
435    /// Reads and discards the next element, whatever it is.
436    ///
437    /// This is how a schema layer steps over an extension it does not know: the
438    /// element is skipped within its declared length, so an unknown tag costs
439    /// what a known one costs and cannot make the reader wander.
440    pub fn skip(&mut self) -> Result<bool> {
441        Ok(self.next_element()?.is_some())
442    }
443
444    /// A reader over the contents of a constructed element read from here.
445    ///
446    /// Refused for a primitive element: its contents are a value rather than
447    /// further elements, and reading them as elements is how a parser is
448    /// talked into finding structure inside an octet string that nobody put
449    /// there.
450    pub fn enter(&self, element: &Element<'a>) -> Result<Reader<'a>> {
451        if !element.tag.is_constructed() {
452            return Err(self.fail_under(ErrorCode::WrongConstruction, element));
453        }
454
455        // Check depth before copying/growing a path: a rejected descent must
456        // not perform the allocation it was supposed to prevent.
457        let depth = self.depth.checked_add(1).ok_or_else(|| {
458            self.fail_under_at(
459                ErrorCode::LimitExceeded(Limit::Depth),
460                element,
461                element.contents_span.start,
462            )
463        })?;
464        self.budget().depth(depth).map_err(|limit| {
465            self.fail_under_at(
466                ErrorCode::LimitExceeded(limit),
467                element,
468                element.contents_span.start,
469            )
470        })?;
471        let mut path = self
472            .path
473            .try_copy_in(self.memory())
474            .map_err(|reason| Error::resource(reason, element.contents_span.start))?;
475        path.push(self.memory(), element.index)
476            .map_err(|reason| Error::resource(reason, element.contents_span.start))?;
477
478        Ok(Reader {
479            data: element.contents,
480            pos: 0,
481            base: element.contents_span.start,
482            depth,
483            next_index: 0,
484            path,
485            encoding: self.encoding,
486            parser: self.parser,
487            execution: self.execution.clone(),
488        })
489    }
490
491    /// Reads an element's contents as an object identifier.
492    pub fn oid(&self, element: &Element<'a>) -> Result<Oid<'a>> {
493        self.primitive(element)?;
494        // The arcs are scanned byte by byte, so the scan is charged to the
495        // shared work budget like the headers are: one long identifier must
496        // not cost time the caller's limits never metered.
497        self.budget()
498            .work_in(element.contents.len() as u64, self.memory())
499            .map_err(|limit| self.fail_under(ErrorCode::LimitExceeded(limit), element))?;
500        value::oid(element.contents).map_err(|code| self.fail_under(code, element))
501    }
502
503    /// Reads an element's contents as an integer.
504    pub fn integer(&self, element: &Element<'a>) -> Result<Integer<'a>> {
505        self.primitive(element)?;
506        value::integer(element.contents).map_err(|code| self.fail_under(code, element))
507    }
508
509    /// Reads an element's contents as a bit string.
510    ///
511    /// The segmented form BER allows for a constructed bit string is refused:
512    /// every bit string this product reads is covered by a signature computed
513    /// over the bytes, where one value with two spellings is one value too
514    /// many.
515    pub fn bit_string(&self, element: &Element<'a>) -> Result<BitString<'a>> {
516        self.primitive(element)?;
517        value::bit_string(element.contents, self.encoding)
518            .map_err(|code| self.fail_under(code, element))
519    }
520
521    /// Reads an element's contents as a boolean.
522    pub fn boolean(&self, element: &Element<'a>) -> Result<bool> {
523        self.primitive(element)?;
524        value::boolean(element.contents, self.encoding)
525            .map_err(|code| self.fail_under(code, element))
526    }
527
528    /// Reads an element's contents as a null, which has none.
529    pub fn null(&self, element: &Element<'a>) -> Result<()> {
530        self.primitive(element)?;
531        value::null(element.contents).map_err(|code| self.fail_under(code, element))
532    }
533
534    /// Reads an element's contents as a real, and answers only whether they
535    /// are a value of the type.
536    ///
537    /// The number itself is not read: no schema this product parses has a
538    /// real in it, and one arrives only inside a value preserved for
539    /// somebody else, who is promised octets that are what they claim.
540    pub fn real(&self, element: &Element<'a>) -> Result<()> {
541        self.primitive(element)?;
542        // The decimal form's field is walked digit by digit, so the scan is
543        // charged to the shared work budget like the headers are: one long
544        // value must not cost time the caller's limits never metered.
545        self.budget()
546            .work_in(element.contents.len() as u64, self.memory())
547            .map_err(|limit| self.fail_under(ErrorCode::LimitExceeded(limit), element))?;
548        value::real(element.contents, self.encoding).map_err(|code| self.fail_under(code, element))
549    }
550
551    /// Reads the next element as an object identifier.
552    pub fn read_oid(&mut self) -> Result<Oid<'a>> {
553        let element = self.expect(Tag::primitive(universal::OID))?;
554        self.oid(&element)
555    }
556
557    /// Reads the next element as an integer.
558    pub fn read_integer(&mut self) -> Result<Integer<'a>> {
559        let element = self.expect(Tag::primitive(universal::INTEGER))?;
560        self.integer(&element)
561    }
562
563    /// Reads the next element as a bit string.
564    pub fn read_bit_string(&mut self) -> Result<BitString<'a>> {
565        let element = self.expect(Tag::primitive(universal::BIT_STRING))?;
566        self.bit_string(&element)
567    }
568
569    /// Reads the next element as a boolean.
570    pub fn read_boolean(&mut self) -> Result<bool> {
571        let element = self.expect(Tag::primitive(universal::BOOLEAN))?;
572        self.boolean(&element)
573    }
574
575    fn primitive(&self, element: &Element<'a>) -> Result<()> {
576        if element.tag.is_constructed() {
577            return Err(self.fail_under(ErrorCode::WrongConstruction, element));
578        }
579        Ok(())
580    }
581
582    /// An error naming an element read from this container.
583    #[must_use]
584    pub fn fail_under(&self, code: ErrorCode, element: &Element<'a>) -> Error {
585        self.fail_under_at(code, element, element.whole.start)
586    }
587
588    fn fail_under_at(&self, code: ErrorCode, element: &Element<'a>, offset: u64) -> Error {
589        match self.path_into(element.index, &[]) {
590            Ok(path) => Error::new(code, offset, path),
591            Err(reason) => Error::resource(reason, offset),
592        }
593    }
594
595    fn fail_at(&self, code: ErrorCode, offset: u64) -> Error {
596        match self.path.try_copy_in(self.memory()) {
597            Ok(path) => Error::new(code, offset, path),
598            Err(reason) => Error::resource(reason, offset),
599        }
600    }
601
602    fn read_header(&mut self) -> Result<Header> {
603        let start = self.offset();
604        self.budget()
605            .element()
606            .map_err(|limit| self.fail_at(ErrorCode::LimitExceeded(limit), start))?;
607
608        let rest = &self.data[self.pos..];
609        header_at(rest, self.encoding, start, self.budget(), self.memory())
610            .map_err(|(code, at)| self.fail_at(code, at))
611    }
612
613    fn finish(&mut self, header: Header) -> Result<Element<'a>> {
614        let contents_at = self.pos + header.len;
615        let contents_start = header.start + header.len as u64;
616
617        let (contents_len, total_len, indefinite) = match header.length {
618            Length::Definite(length) => {
619                self.budget()
620                    .length(length)
621                    .map_err(|limit| self.fail_at(ErrorCode::LimitExceeded(limit), header.start))?;
622
623                let length = usize::try_from(length)
624                    .map_err(|_| self.fail_at(ErrorCode::LengthTooLarge, header.start))?;
625
626                let end = contents_at
627                    .checked_add(length)
628                    .ok_or_else(|| self.fail_at(ErrorCode::LengthTooLarge, header.start))?;
629
630                if end > self.data.len() {
631                    return Err(self.fail_at(ErrorCode::UnexpectedEnd, header.start));
632                }
633
634                (length, header.len + length, false)
635            }
636            Length::Indefinite => {
637                if !header.tag.is_constructed() {
638                    return Err(self.fail_at(ErrorCode::WrongConstruction, header.start));
639                }
640                let contents_len =
641                    self.scan_to_end_of_contents(contents_at, contents_start, self.next_index)?;
642
643                // An indefinite element declares no length, so nothing has held
644                // it to one yet. Its size is what the scan just measured, and a
645                // container assembled from many small children would otherwise
646                // pass a budget its declared-length siblings could not.
647                self.budget()
648                    .length(contents_len as u64)
649                    .map_err(|limit| self.fail_at(ErrorCode::LimitExceeded(limit), header.start))?;
650
651                // Two further bytes for the end-of-contents marker, which is
652                // exactly two: the scan refuses any other spelling of it.
653                (contents_len, header.len + contents_len + 2, true)
654            }
655        };
656
657        let contents = &self.data[contents_at..contents_at + contents_len];
658        // The element as it arrived, header and any end-of-contents marker
659        // included. Both bounds were established above, so the slice exists.
660        let bytes = &self.data[self.pos..self.pos + total_len];
661        let index = self.next_index;
662
663        self.pos += total_len;
664        self.next_index = self
665            .next_index
666            .checked_add(1)
667            .ok_or_else(|| self.fail_at(ErrorCode::LimitExceeded(Limit::Elements), header.start))?;
668
669        Ok(Element {
670            tag: header.tag,
671            contents,
672            bytes,
673            contents_span: Span {
674                start: contents_start,
675                length: contents_len as u64,
676            },
677            whole: Span {
678                start: header.start,
679                length: total_len as u64,
680            },
681            indefinite,
682            index,
683        })
684    }
685
686    /// Finds where an indefinite-length element's contents end.
687    ///
688    /// Walks the elements inside it with an explicit stack rather than by
689    /// recursing, so a document nested a million deep is refused by the depth
690    /// budget instead of ending the process.
691    ///
692    /// A measurement, not a reading: the elements it steps over are charged to
693    /// the element budget later, where they are actually read. This costs
694    /// work.
695    fn scan_to_end_of_contents(
696        &self,
697        from: usize,
698        from_offset: u64,
699        own_index: u32,
700    ) -> Result<usize> {
701        let mut cursor = from;
702        let mut offset = from_offset;
703
704        // The index of the next element at each level entered so far, so an
705        // error inside nested contents names where it is rather than naming the
706        // container the scan started from.
707        let mut trail = self.memory().vector::<u32>();
708        let mut index: u32 = 0;
709
710        // Assembled only where an error is returned: building it per header is
711        // work proportional to depth times children, which the work budget
712        // does not count.
713        let fail = |code: ErrorCode, at: u64, trail: &[u32]| match self.path_into(own_index, trail)
714        {
715            Ok(path) => Error::new(code, at, path),
716            Err(reason) => Error::resource(reason, at),
717        };
718        let spent =
719            |limit: Limit, at: u64, trail: &[u32]| fail(ErrorCode::LimitExceeded(limit), at, trail);
720
721        loop {
722            let depth = u32::try_from(trail.len())
723                .ok()
724                .and_then(|nested| self.depth.checked_add(nested))
725                .and_then(|depth| depth.checked_add(1))
726                .ok_or_else(|| spent(Limit::Depth, offset, &trail))?;
727            self.budget()
728                .depth(depth)
729                .map_err(|limit| spent(limit, offset, &trail))?;
730
731            let rest = self
732                .data
733                .get(cursor..)
734                .filter(|rest| !rest.is_empty())
735                .ok_or_else(|| fail(ErrorCode::UnterminatedContents, from_offset, &trail))?;
736
737            let header = header_at(rest, self.encoding, offset, self.budget(), self.memory())
738                .map_err(|(code, at)| fail(code, at, &trail))?;
739            let inner_tag = header.tag;
740            let inner_length = header.length;
741            let header_len = header.len;
742
743            if inner_tag.is_end_of_contents() {
744                // Exactly two octets. A zero length written the long way reads
745                // as a zero length, and taking it for the marker would end the
746                // element short and leave the rest of the marker to be read as
747                // another element.
748                if header_len != 2 || !matches!(inner_length, Length::Definite(0)) {
749                    return Err(fail(ErrorCode::MalformedEndOfContents, offset, &trail));
750                }
751                match trail.pop() {
752                    // This one closes the element the scan was opened for.
753                    None => return Ok(cursor - from),
754                    // Back at the level that container sat on, with it read.
755                    Some(outer) => {
756                        index = outer
757                            .checked_add(1)
758                            .ok_or_else(|| spent(Limit::Elements, offset, &trail))?;
759                    }
760                }
761                cursor += header_len;
762                offset += header_len as u64;
763                continue;
764            }
765
766            let step = match inner_length {
767                Length::Indefinite => {
768                    if !inner_tag.is_constructed() {
769                        return Err(fail(ErrorCode::WrongConstruction, offset, &trail));
770                    }
771                    // The index this container itself sits at, so a fault
772                    // inside it is reported under it rather than beside it.
773                    trail
774                        .try_push(index)
775                        .map_err(|reason| Error::resource(reason, offset))?;
776                    index = 0;
777                    header_len
778                }
779                Length::Definite(length) => {
780                    self.budget()
781                        .length(length)
782                        .map_err(|limit| spent(limit, offset, &trail))?;
783                    let length = usize::try_from(length)
784                        .map_err(|_| fail(ErrorCode::LengthTooLarge, offset, &trail))?;
785                    index = index
786                        .checked_add(1)
787                        .ok_or_else(|| spent(Limit::Elements, offset, &trail))?;
788                    header_len
789                        .checked_add(length)
790                        .ok_or_else(|| fail(ErrorCode::LengthTooLarge, offset, &trail))?
791                }
792            };
793
794            cursor = cursor
795                .checked_add(step)
796                .ok_or_else(|| fail(ErrorCode::LengthTooLarge, offset, &trail))?;
797            if cursor > self.data.len() {
798                return Err(fail(ErrorCode::UnexpectedEnd, offset, &trail));
799            }
800            offset += step as u64;
801        }
802    }
803
804    /// The path to a point inside an element of this container: this
805    /// container's path, the element's own index, then the index of each
806    /// nested container entered on the way.
807    fn path_into(
808        &self,
809        own_index: u32,
810        trail: &[u32],
811    ) -> core::result::Result<Path, crate::memory::MemoryError> {
812        let mut path = self.path.try_copy_in(self.memory())?;
813        path.push(self.memory(), own_index)?;
814        for index in trail {
815            path.push(self.memory(), *index)?;
816        }
817        Ok(path)
818    }
819}
820
821#[derive(Clone, Copy)]
822struct Header {
823    tag: Tag,
824    length: Length,
825    start: u64,
826    len: usize,
827}
828
829/// Both ordinary parsing and indefinite scans use the same pre-admission path.
830fn header_at(
831    input: &[u8],
832    encoding: Encoding,
833    start: u64,
834    budget: &Budget,
835    execution: &Memory,
836) -> core::result::Result<Header, (ErrorCode, u64)> {
837    // Common short headers use one aggregate atomic admission for both bytes.
838    // Extra high-tag octets and long lengths spend only before they are examined.
839    budget
840        .work_in(2, execution)
841        .map_err(|limit| (ErrorCode::LimitExceeded(limit), start))?;
842    let mut credit = 2;
843    let mut charge = |amount: u64| {
844        if amount <= credit {
845            credit -= amount;
846            return Ok(());
847        }
848        let additional = amount - credit;
849        credit = 0;
850        budget
851            .work_in(additional, execution)
852            .map_err(ErrorCode::LimitExceeded)
853    };
854    let (tag, tag_len) = tag::read_accounted(input, start, &mut charge)?;
855    let (length, length_len) = length::read_accounted(
856        &input[tag_len..],
857        encoding,
858        start + tag_len as u64,
859        &mut charge,
860    )?;
861    Ok(Header {
862        tag,
863        length,
864        start,
865        len: tag_len + length_len,
866    })
867}
868
869#[cfg(test)]
870mod tests;