Skip to main content

oxirush_aper/
reader.rs

1//! Reading aligned PER: the fields of ITU-T X.691 (02/2021), from octets.
2
3use alloc::borrow::Cow;
4use alloc::string::String;
5use alloc::vec::Vec;
6
7use crate::{BitString, Bits, Error, Fault, Faults, ObjectIdentifier, Octets, UNBOUNDED};
8
9/// How many items a fragment of 16K items has (X.691 §11.9.3.8).
10const SIXTEEN_K: usize = 16384;
11
12/// The most that a list reserves before its elements are read, in bytes: a count is
13/// what a peer claims, and the elements are what it sent.
14const RESERVED: usize = 4096;
15
16/// A reader of aligned PER: the octets of an encoding, and how far they are read.
17///
18/// Each method reads one field of ITU-T X.691 and moves on. A field that is
19/// octet-aligned skips the bits up to the next octet first. The bounds of a constraint
20/// are arguments, which a caller writes as constants.
21///
22/// A value that is whole, in another form than the one that its clause gives it, is
23/// read, as the encoder of a peer may write it: a length of 127 or less in two octets,
24/// a fragment that is not the largest, a small number in the form of a larger one, a
25/// whole number in more octets than it needs, padding bits that are not zero, and an
26/// arc of an object identifier that starts with an octet that holds nothing. A
27/// reader that [`noting`](Self::noting) made notes each, [`faults`](Self::faults) has
28/// what it noted, and [`decode_strict`](crate::decode_strict) refuses it.
29///
30/// ```
31/// use oxirush_aper::Reader;
32///
33/// // INTEGER (0..7), then INTEGER (0..65535), which is two octets after padding
34/// let mut reader = Reader::new(&[0b1010_0000, 0x12, 0x34]);
35/// assert_eq!(reader.unsigned(0, 7)?, 5);
36/// assert_eq!(reader.unsigned(0, 65535)?, 0x1234);
37/// # Ok::<(), oxirush_aper::Error>(())
38/// ```
39///
40/// A value that holds octets borrows them from the octets of the reader, and lives as
41/// long as they do.
42#[derive(Clone, Debug)]
43pub struct Reader<'a> {
44    octets: &'a [u8],
45    /// How many octets follow those that the reader takes, as a count of bits holds no
46    /// more than `usize::MAX / 8` of them: what [`finish`](Self::finish) refuses too.
47    beyond: usize,
48    /// How many bits are read.
49    at: usize,
50    /// What was read in another form than the one of its clause, when the reader
51    /// notes it.
52    faults: Faults,
53    noting: bool,
54}
55
56impl<'a> Reader<'a> {
57    /// A reader at the first bit of `octets`.
58    #[inline]
59    pub fn new(octets: &'a [u8]) -> Self {
60        // The position is a count of bits: 512 MiB of octets at most on 32 bits.
61        Self::taking(octets, usize::MAX / 8)
62    }
63
64    /// A reader of the first `most` of `octets`, and of none of those that follow,
65    /// which only [`finish`](Self::finish) counts.
66    #[inline]
67    fn taking(octets: &'a [u8], most: usize) -> Self {
68        let beyond = octets.len().saturating_sub(most);
69        Self {
70            octets: &octets[..octets.len() - beyond],
71            beyond,
72            at: 0,
73            faults: Faults::new(),
74            noting: false,
75        }
76    }
77
78    /// A reader at the first bit of `octets` that notes what it reads in another form
79    /// than the one that its clause gives: see [`Fault`], and [`faults`](Self::faults).
80    /// It reads what a reader of [`new`](Self::new) reads, which looks at no padding
81    /// bit and notes nothing.
82    ///
83    /// ```
84    /// use oxirush_aper::{Fault, Reader, UNBOUNDED};
85    ///
86    /// // An OCTET STRING of one octet, whose length is in two octets
87    /// let mut reader = Reader::noting(&[0x80, 0x01, 0xaa]);
88    /// assert_eq!(reader.octet_string(0, UNBOUNDED)?, [0xaa]);
89    /// assert_eq!(reader.faults()[0].fault, Fault::LengthInTwoOctets);
90    /// # Ok::<(), oxirush_aper::Error>(())
91    /// ```
92    #[inline]
93    pub fn noting(octets: &'a [u8]) -> Self {
94        let mut reader = Self::new(octets);
95        reader.noting = true;
96        reader
97    }
98
99    /// What a reader that [`noting`](Self::noting) made read so far in another form
100    /// than the one that its clause gives, each with the bit of the octets at which it
101    /// is. None for a reader of [`new`](Self::new).
102    #[inline]
103    pub fn faults(&self) -> &Faults {
104        &self.faults
105    }
106
107    /// Note a fault at a bit, when the reader notes: no part of reading octets that
108    /// are written by the clauses.
109    #[cold]
110    #[inline(never)]
111    fn note(&mut self, fault: Fault, bit: usize) {
112        if self.noting {
113            self.faults.push(fault, bit);
114        }
115    }
116
117    /// Note the bits up to the next octet boundary when one of them is not zero (X.691
118    /// §11.1.4). They are not skipped here.
119    #[inline]
120    fn padding(&mut self) {
121        let shift = self.at & 7;
122        if self.noting
123            && shift != 0
124            && let Some(octet) = self.octets.get(self.at >> 3)
125            && octet & (0xff >> shift) != 0
126        {
127            self.note(Fault::Padding, self.at);
128        }
129    }
130
131    /// How many bits are read.
132    #[inline]
133    pub fn position(&self) -> usize {
134        self.at
135    }
136
137    /// How many bits are left.
138    #[inline]
139    pub fn remaining(&self) -> usize {
140        self.octets.len() * 8 - self.at
141    }
142
143    /// The octets that are left, from the next octet boundary.
144    #[inline]
145    pub fn rest(&self) -> &'a [u8] {
146        &self.octets[self.at.div_ceil(8)..]
147    }
148
149    /// The end of a complete encoding (X.691 §11.1.4): no octet follows the value,
150    /// whose last octet may have padding bits. An encoding of no bit is one zero octet.
151    /// The octets that follow the most that a reader takes, `usize::MAX / 8` of them,
152    /// follow the value too.
153    #[inline]
154    pub fn finish(&self) -> Result<(), Error> {
155        let rest = self.rest();
156        if self.beyond == 0 && (rest.is_empty() || (self.at == 0 && self.octets == [0])) {
157            return Ok(());
158        }
159        Err(followed(rest.len() + self.beyond))
160    }
161
162    // ── Bits and octets ─────────────────────────────────────────────────────
163
164    /// One bit: a BOOLEAN (X.691 §12), and the bit of an extension marker or of a
165    /// member that may be absent.
166    #[inline]
167    pub fn bit(&mut self) -> Result<bool, Error> {
168        let Some(octet) = self.octets.get(self.at >> 3) else {
169            return Err(Error::ended());
170        };
171        let bit = octet & (0x80 >> (self.at & 7)) != 0;
172        self.at += 1;
173        Ok(bit)
174    }
175
176    /// The next `count` bits as a number, the first bit the most significant: 64 bits
177    /// at most. They are not aligned.
178    #[inline]
179    pub fn bits(&mut self, count: usize) -> Result<u64, Error> {
180        debug_assert!(count <= 64);
181        let (first, shift) = (self.at >> 3, self.at & 7);
182        if count > self.remaining() {
183            return Err(Error::ended());
184        }
185        self.at += count;
186        // Bits within one octet, as the index of an ENUMERATED and the bits of a
187        // preamble are: the octet is there, as the bits are.
188        if shift + count <= 8 {
189            let octet = self.octets.get(first).copied().unwrap_or(0);
190            let (wide, mask) = (u16::from(octet), (1u16 << count) - 1);
191            return Ok(u64::from(wide >> (8 - shift - count) & mask));
192        }
193        // Eight octets hold the bits, unless they start late in the first one.
194        if let Some(word) = self.octets.get(first..first + 8)
195            && shift + count <= 64
196        {
197            let word = u64::from_be_bytes([
198                word[0], word[1], word[2], word[3], word[4], word[5], word[6], word[7],
199            ]);
200            return Ok((word << shift) >> (64 - count));
201        }
202        Ok(self.bits_near_the_end(first, shift, count))
203    }
204
205    /// `count` bits from the bit `shift` of the octet `first`, which are there and are
206    /// in more than one octet: those near the end of the octets, and 64 bits that
207    /// start within an octet.
208    fn bits_near_the_end(&self, first: usize, shift: usize, count: usize) -> u64 {
209        let last = (first * 8 + shift + count).div_ceil(8);
210        let held = &self.octets[first..last];
211        // Nine octets at most: eight of them in a word, and the bits of the ninth.
212        let (whole, rest) = held.split_at(held.len().min(8));
213        let mut word = [0; 8];
214        word[..whole.len()].copy_from_slice(whole);
215        let word = u64::from_be_bytes(word);
216        match rest.first() {
217            None => (word << shift) >> (64 - count),
218            // The 64 bits from `shift`, of which the last `shift` are in the ninth
219            // octet, then the first `count` of them.
220            Some(ninth) => (word << shift | u64::from(*ninth) >> (8 - shift)) >> (64 - count),
221        }
222    }
223
224    /// Skip the bits up to the next octet boundary: the padding of an octet-aligned
225    /// field, and that of the end of a complete encoding (X.691 §11.1.4). Bits of it
226    /// that are not zero are noted.
227    #[inline]
228    pub fn align(&mut self) {
229        self.padding();
230        self.at = (self.at + 7) & !7;
231    }
232
233    /// One octet, octet-aligned.
234    #[inline]
235    pub fn octet(&mut self) -> Result<u8, Error> {
236        self.padding();
237        let at = (self.at + 7) >> 3;
238        let Some(octet) = self.octets.get(at) else {
239            return Err(Error::ended());
240        };
241        self.at = (at + 1) << 3;
242        Ok(*octet)
243    }
244
245    /// The next `count` octets, octet-aligned.
246    #[inline]
247    pub fn octets(&mut self, count: usize) -> Result<&'a [u8], Error> {
248        self.padding();
249        let start = (self.at + 7) >> 3;
250        let held = start
251            .checked_add(count)
252            .and_then(|end| self.octets.get(start..end));
253        let Some(held) = held else {
254            return Err(Error::ended());
255        };
256        self.at = (start + count) << 3;
257        Ok(held)
258    }
259
260    /// The next `count` bits from an octet boundary, as the octets that hold them, the
261    /// last one padded with zero bits. What follows them is not aligned.
262    fn aligned_bits(&mut self, count: usize) -> Result<Octets<'a>, Error> {
263        self.padding();
264        let start = (self.at + 7) >> 3;
265        let length = count.div_ceil(8);
266        let held = start
267            .checked_add(length)
268            .and_then(|end| self.octets.get(start..end));
269        let Some(held) = held else {
270            return Err(Error::ended());
271        };
272        self.at = (start << 3) + count;
273        let unused = length * 8 - count;
274        match held.last() {
275            // The bits after the last one are those of the next field, or padding
276            // that is not zero.
277            Some(last) if (last.trailing_zeros() as usize) < unused => {
278                let mut owned = held.to_vec();
279                owned[length - 1] &= 0xff << unused;
280                Ok(Octets::owned(owned))
281            }
282            _ => Ok(Octets::borrowed(held)),
283        }
284    }
285
286    // ── Whole numbers ───────────────────────────────────────────────────────
287
288    /// A constrained whole number (X.691 §11.5) of `lower..=upper`, as an INTEGER of
289    /// that constraint is encoded (§13.2.2): no bit for one value, a bit-field for a
290    /// range of 255 values at most, one octet for 256, two octets up to 64K, and
291    /// above that the number of its octets, then its octets.
292    #[inline]
293    pub fn unsigned(&mut self, lower: u64, upper: u64) -> Result<u64, Error> {
294        debug_assert!(lower <= upper);
295        let span = upper.wrapping_sub(lower);
296        let offset = self.offset(span)?;
297        if offset > span {
298            let value = i128::from(lower) + i128::from(offset);
299            return Err(Error::number_read_outside(
300                value,
301                lower.into(),
302                upper.into(),
303            ));
304        }
305        Ok(lower + offset)
306    }
307
308    /// A constrained whole number of `lower..=upper`, where the bounds may be negative.
309    #[inline]
310    pub fn signed(&mut self, lower: i64, upper: i64) -> Result<i64, Error> {
311        debug_assert!(lower <= upper);
312        let span = (upper as u64).wrapping_sub(lower as u64);
313        let offset = self.offset(span)?;
314        if offset > span {
315            let value = i128::from(lower) + i128::from(offset);
316            return Err(Error::number_read_outside(
317                value,
318                lower.into(),
319                upper.into(),
320            ));
321        }
322        Ok((lower as u64).wrapping_add(offset) as i64)
323    }
324
325    /// How far a constrained whole number is from its lower bound, for a constraint
326    /// whose upper bound is `span` above the lower one. The field may hold more than
327    /// `span`.
328    #[inline]
329    fn offset(&mut self, span: u64) -> Result<u64, Error> {
330        match span {
331            0 => Ok(0),
332            1..=254 => self.bits(64 - span.leading_zeros() as usize),
333            255 => self.octet().map(u64::from),
334            256..=65535 => {
335                let octets = self.octets(2)?;
336                Ok(u64::from(u16::from_be_bytes([octets[0], octets[1]])))
337            }
338            _ => self.offset_with_length(span),
339        }
340    }
341
342    /// The indefinite length case (X.691 §11.5.7.4, §13.2.6 a): the number of octets,
343    /// which is constrained to what the range takes, then the octets.
344    fn offset_with_length(&mut self, span: u64) -> Result<u64, Error> {
345        let most = (64 - span.leading_zeros() as usize).div_ceil(8);
346        let length_bits = usize::BITS as usize - (most - 1).leading_zeros() as usize;
347        // The field of the length holds eight at most.
348        let length = self.bits(length_bits)? as usize + 1;
349        let octets = self.octets(length)?;
350        // The least octets that hold the number (§11.3.6).
351        if length > 1 && octets[0] == 0 {
352            self.note(Fault::LongNumber, self.at - length * 8);
353        }
354        Ok(octets
355            .iter()
356            .fold(0, |number, octet| number << 8 | u64::from(*octet)))
357    }
358
359    /// An INTEGER whose constraint `lower..=upper` has an extension marker (X.691
360    /// §13.1): a bit, then the number within the constraint, or any number as an
361    /// unconstrained one. The bindings hold it in 64 bits without a sign.
362    ///
363    /// # Errors
364    ///
365    /// A number outside the constraint that is negative, or of more than 64 bits, is an
366    /// error: the bindings have no type for it.
367    pub fn unsigned_extensible(&mut self, lower: u64, upper: u64) -> Result<u64, Error> {
368        if !self.bit()? {
369            return self.unsigned(lower, upper);
370        }
371        let number = self.whole_number(true)?;
372        u64::try_from(number).map_err(|_| Error::does_not_fit(64))
373    }
374
375    /// An INTEGER whose constraint `lower..=upper` has an extension marker, where the
376    /// bounds may be negative. The bindings hold it in 64 bits with a sign.
377    pub fn signed_extensible(&mut self, lower: i64, upper: i64) -> Result<i64, Error> {
378        if !self.bit()? {
379            return self.signed(lower, upper);
380        }
381        self.unconstrained()
382    }
383
384    /// An unconstrained whole number (X.691 §11.8), as an INTEGER without a
385    /// PER-visible constraint is encoded (§13.2.4): the number of its octets, then
386    /// its octets in two's complement.
387    pub fn unconstrained(&mut self) -> Result<i64, Error> {
388        let number = self.whole_number(true)?;
389        i64::try_from(number).map_err(|_| Error::does_not_fit(64))
390    }
391
392    /// A semi-constrained whole number (X.691 §11.7), as an INTEGER with a lower
393    /// bound and no upper one is encoded (§13.2.3): the number of the octets of what
394    /// it has above `lower`, then these octets.
395    pub fn semi_constrained(&mut self, lower: i64) -> Result<i64, Error> {
396        let above = self.whole_number(false)?;
397        let number = i128::from(lower) + above;
398        i64::try_from(number).map_err(|_| Error::does_not_fit(64))
399    }
400
401    /// A semi-constrained whole number whose lower bound is not negative, in 64 bits
402    /// without a sign.
403    pub fn semi_constrained_unsigned(&mut self, lower: u64) -> Result<u64, Error> {
404        let above = self.whole_number(false)?;
405        let number = i128::from(lower) + above;
406        u64::try_from(number).map_err(|_| Error::does_not_fit(64))
407    }
408
409    /// A whole number after the unconstrained length of its octets: in two's
410    /// complement when it is `signed`.
411    ///
412    /// A writer gives a number the least octets that hold it (X.691 §11.3.6, §11.4.6).
413    /// A reader takes octets that only extend the sign before them, and notes them, as
414    /// long as the octets are no more than a number of 64 bits may have: eight, and
415    /// nine in two's complement, where a number of 2^63 or more has a zero octet first.
416    /// More octets are refused whatever they hold.
417    fn whole_number(&mut self, signed: bool) -> Result<i128, Error> {
418        let octets = self.open_type()?;
419        if octets.is_empty() {
420            return Err(Error::decode("a whole number has no octet"));
421        }
422        if octets.len() > if signed { 9 } else { 8 } {
423            return Err(Error::does_not_fit(64));
424        }
425        // The least octets: the first eight bits are not all zero, and in two's
426        // complement the first nine are neither all zero nor all ones.
427        if let [first, second, ..] = &octets[..] {
428            let extends = match signed {
429                true => (*first == 0 && *second < 0x80) || (*first == 0xff && *second >= 0x80),
430                false => *first == 0,
431            };
432            if extends {
433                self.note(Fault::LongNumber, self.at - octets.len() * 8);
434            }
435        }
436        let negative = signed && octets[0] & 0x80 != 0;
437        let start: i128 = if negative { -1 } else { 0 };
438        let number = octets.iter();
439        Ok(number.fold(start, |number, octet| number << 8 | i128::from(*octet)))
440    }
441
442    /// A normally small non-negative whole number (X.691 §11.6): the index of an
443    /// alternative or of a value that a later version adds.
444    pub fn small(&mut self) -> Result<u64, Error> {
445        if !self.bit()? {
446            return self.bits(6);
447        }
448        let start = self.at - 1;
449        let number = self.semi_constrained_unsigned(0)?;
450        // 63 and less are six bits after a zero bit (§11.6.1).
451        if number <= 63 {
452            self.note(Fault::SmallNumberAsLarge, start);
453        }
454        Ok(number)
455    }
456
457    // ── Lengths ─────────────────────────────────────────────────────────────
458
459    /// An unconstrained length determinant (X.691 §11.9.3.5 to §11.9.3.8): how many
460    /// items follow it, and whether another length follows these items, which then
461    /// are a fragment of one to four times 16K items.
462    ///
463    /// ```
464    /// use oxirush_aper::Reader;
465    ///
466    /// // 5, then 130 in two octets, then a fragment of 16384
467    /// let mut reader = Reader::new(&[0x05, 0x80, 0x82, 0xc1]);
468    /// assert_eq!(reader.length()?, (5, false));
469    /// assert_eq!(reader.length()?, (130, false));
470    /// assert_eq!(reader.length()?, (16384, true));
471    /// # Ok::<(), oxirush_aper::Error>(())
472    /// ```
473    #[inline]
474    pub fn length(&mut self) -> Result<(usize, bool), Error> {
475        let first = self.octet()?;
476        match first {
477            0..=0x7f => Ok((usize::from(first), false)),
478            0x80..=0xbf => {
479                let second = self.octet()?;
480                let length = usize::from(first & 0x3f) << 8 | usize::from(second);
481                // 127 and less are one octet (§11.9.3.6).
482                if length < 0x80 {
483                    self.note(Fault::LengthInTwoOctets, self.at - 16);
484                }
485                Ok((length, false))
486            }
487            0xc1..=0xc4 => Ok((usize::from(first & 0x3f) * SIXTEEN_K, true)),
488            _ => Err(Error::decode(
489                "a fragment has one to four times 16384 items",
490            )),
491        }
492    }
493
494    /// The length determinant that follows a fragment of `fragment` items, as
495    /// [`length`](Self::length) reads it: how many items follow it, and whether they
496    /// are a fragment too.
497    ///
498    /// A fragment is the largest that the items allow (X.691 §11.9.3.8.1), so the one
499    /// before another has four times 16K items. A smaller one is read, and a reader
500    /// that notes its faults notes it.
501    ///
502    /// ```
503    /// use oxirush_aper::{Fault, Reader};
504    ///
505    /// // 32768 items in two fragments of 16384, where one fragment holds them
506    /// let mut reader = Reader::noting(&[0xc1, 0xc1, 0x00]);
507    /// let (first, _) = reader.length()?;
508    /// let (second, _) = reader.length_after(first)?;
509    /// assert_eq!(reader.length_after(second)?, (0, false));
510    /// assert_eq!(reader.faults()[0].fault, Fault::SmallFragment);
511    /// # Ok::<(), oxirush_aper::Error>(())
512    /// ```
513    #[inline]
514    pub fn length_after(&mut self, fragment: usize) -> Result<(usize, bool), Error> {
515        let (count, more) = self.length()?;
516        if more && fragment < 4 * SIXTEEN_K {
517            self.note(Fault::SmallFragment, self.at - 8);
518        }
519        Ok((count, more))
520    }
521
522    /// The size of a string or of a list whose size constraint is `lower..=upper`,
523    /// with an upper bound below 64K: a constrained whole number (X.691 §11.9.3.3).
524    /// For a size of one value there is no field.
525    #[inline]
526    pub fn size(&mut self, lower: usize, upper: usize) -> Result<usize, Error> {
527        debug_assert!(lower <= upper && upper < 65536);
528        let span = upper.wrapping_sub(lower) as u64;
529        let offset = self.offset(span)?;
530        if offset > span {
531            return Err(Error::size_read_outside(
532                lower.saturating_add(offset as usize),
533                lower,
534                Some(upper),
535            ));
536        }
537        Ok(lower + offset as usize)
538    }
539
540    /// Whether `size`, which was read after an unconstrained length, is within the size
541    /// constraint `lower..=upper`: the elements of a list in fragments are counted by
542    /// its reader.
543    pub fn check_size(size: usize, lower: usize, upper: usize) -> Result<(), Error> {
544        check_size(size, lower, upper)
545    }
546
547    /// The bitmap of the extension additions (X.691 §19.7, §19.8) after its length, a
548    /// normally small length (§11.9.3.4): 64 bits at most have their length, less one,
549    /// in six bits, and more bits an unconstrained length.
550    ///
551    /// The clauses leave a sender one encoding, and a reader takes no other: the length
552    /// is one at least (§11.9.3.1 a)), 64 bits at most are not counted in the form of
553    /// more, and one addition at least is present, as the extension bit is set for
554    /// nothing else (§19.1).
555    fn addition_bitmap(&mut self) -> Result<BitString<'a>, Error> {
556        const NONE: &str =
557            "the extension bit of a SEQUENCE is set, and it has no extension addition";
558        let bitmap = if self.bit()? {
559            let bitmap = self.bit_string_in_fragments()?;
560            match bitmap.len() {
561                0 => return Err(Error::decode(NONE)),
562                1..=64 => {
563                    return Err(Error::decode(
564                        "the bitmap of 64 extension additions at most has its length in six bits",
565                    ));
566                }
567                _ => bitmap,
568            }
569        } else {
570            let count = self.bits(6)? as usize + 1;
571            self.bit_field(count)?
572        };
573        if (0..bitmap.len()).all(|addition| bitmap.get(addition) != Some(true)) {
574            return Err(Error::decode(NONE));
575        }
576        Ok(bitmap)
577    }
578
579    // ── ENUMERATED and CHOICE ───────────────────────────────────────────────
580
581    /// The index of a value of an ENUMERATED (X.691 §14) that has `root` values before
582    /// its extension marker and `additions` after it, when it is `extensible`. The
583    /// values are counted in the order of their numbers, those of the root first: the
584    /// first addition has the index `root`.
585    ///
586    /// # Errors
587    ///
588    /// An index that no value has is an error: a field of two bits holds four indexes
589    /// for three values, and a later version may add a value.
590    #[inline]
591    pub fn enumerated(
592        &mut self,
593        root: u64,
594        additions: u64,
595        extensible: bool,
596    ) -> Result<u64, Error> {
597        match self.index(root, extensible)? {
598            (index, false) if index < root => Ok(index),
599            (index, true) if index < additions => Ok(root + index),
600            (index, addition) => Err(no_index(index, addition, "value of the ENUMERATED")),
601        }
602    }
603
604    /// The index of the alternative of a CHOICE (X.691 §23) that has `root`
605    /// alternatives before its extension marker and `additions` after it, when it is
606    /// `extensible`. The first addition has the index `root`, and its value follows in
607    /// an open type.
608    ///
609    /// # Errors
610    ///
611    /// An index that no alternative has is an error.
612    #[inline]
613    pub fn choice(&mut self, root: u64, additions: u64, extensible: bool) -> Result<u64, Error> {
614        match self.index(root, extensible)? {
615            (index, false) if index < root => Ok(index),
616            (index, true) if index < additions => Ok(root + index),
617            (index, addition) => Err(no_index(index, addition, "alternative of the CHOICE")),
618        }
619    }
620
621    /// An index among `root` values or alternatives, or among the additions: which of
622    /// the two it is.
623    #[inline]
624    fn index(&mut self, root: u64, extensible: bool) -> Result<(u64, bool), Error> {
625        debug_assert!(root > 0);
626        if extensible && self.bit()? {
627            return Ok((self.small()?, true));
628        }
629        Ok((self.offset(root - 1)?, false))
630    }
631
632    // ── SEQUENCE ────────────────────────────────────────────────────────────
633
634    /// Skip the extension additions of a SEQUENCE whose extension bit is set (X.691
635    /// §19.7 to §19.9): the bitmap of their presence, then an open type for each one
636    /// that is present. A later version of a specification adds them, and a reader of
637    /// an earlier one does not know them.
638    ///
639    /// ```
640    /// use oxirush_aper::Reader;
641    ///
642    /// // Two additions that this reader does not know, the second present, then the
643    /// // octet of what follows the SEQUENCE
644    /// let mut reader = Reader::new(&[0b0000_0010, 0b1000_0000, 0x01, 0xaa, 0x07]);
645    /// reader.skip_additions()?;
646    /// assert_eq!(reader.unsigned(0, 255)?, 7);
647    ///
648    /// // A bitmap of two additions of which none is present has no encoding
649    /// assert!(Reader::new(&[0b0000_0010, 0b0000_0000]).skip_additions().is_err());
650    /// # Ok::<(), oxirush_aper::Error>(())
651    /// ```
652    ///
653    /// # Errors
654    ///
655    /// What the clauses give no encoding for is an error: a bitmap of no bit or of
656    /// which no bit is set, as the extension bit is set when an addition is present
657    /// (§19.1, §19.8); a bitmap of 64 bits at most whose length is in the form of more
658    /// (§11.9.3.4); and an addition of no octet (§11.1.3.1).
659    pub fn skip_additions(&mut self) -> Result<(), Error> {
660        let additions = self.additions()?;
661        additions.skip_rest(self)
662    }
663
664    /// The extension additions of a SEQUENCE whose extension bit is set: which of them
665    /// are present. Each one that is present follows in an open type, in their order.
666    /// The bitmap is refused as [`skip_additions`](Self::skip_additions) refuses it.
667    ///
668    /// ```
669    /// use oxirush_aper::Reader;
670    ///
671    /// // Two additions, of which the second is present: an open type of one octet
672    /// let mut reader = Reader::new(&[0b0000_0010, 0b1000_0000, 0x01, 0xaa]);
673    /// let mut additions = reader.additions()?;
674    /// assert!(!additions.present());
675    /// assert!(additions.present());
676    /// assert_eq!(reader.open_type()?, [0xaa]);
677    /// additions.skip_rest(&mut reader)?;
678    /// # Ok::<(), oxirush_aper::Error>(())
679    /// ```
680    pub fn additions(&mut self) -> Result<Additions<'a>, Error> {
681        let bitmap = self.addition_bitmap()?;
682        Ok(Additions { bitmap, next: 0 })
683    }
684
685    // ── OCTET STRING ────────────────────────────────────────────────────────
686
687    /// An OCTET STRING of `N` octets (X.691 §17.6, §17.7): a bit-field for two octets
688    /// at most, and octet-aligned otherwise.
689    #[inline]
690    pub fn octet_array<const N: usize>(&mut self) -> Result<[u8; N], Error> {
691        let mut array = [0; N];
692        if N > 2 {
693            array.copy_from_slice(self.octets(N)?);
694        } else {
695            for octet in &mut array {
696                *octet = self.bits(8)? as u8;
697            }
698        }
699        Ok(array)
700    }
701
702    /// An OCTET STRING of the size constraint `lower..=upper` (X.691 §17), with
703    /// [`UNBOUNDED`] for no upper bound. The octets are borrowed.
704    ///
705    /// A string of 16384 octets or more is in fragments when its size has no bound
706    /// below 64K, and is then copied.
707    #[inline]
708    pub fn octet_string(&mut self, lower: usize, upper: usize) -> Result<Octets<'a>, Error> {
709        if upper >= 65536 {
710            let octets = self.octets_in_fragments()?;
711            return check_size(octets.len(), lower, upper).map(|()| octets);
712        }
713        if lower == upper {
714            // Two octets at most are a bit-field.
715            return match lower {
716                0 => Ok(Octets::EMPTY),
717                1..=2 => {
718                    let short = self.bits(lower * 8)?.to_be_bytes();
719                    Ok(Octets::owned(short[8 - lower..].to_vec()))
720                }
721                _ => self.octets(lower).map(Octets::borrowed),
722            };
723        }
724        match self.size(lower, upper)? {
725            // Nothing is added for no octet, and no padding.
726            0 => Ok(Octets::EMPTY),
727            size => self.octets(size).map(Octets::borrowed),
728        }
729    }
730
731    /// An OCTET STRING whose size constraint `lower..=upper` has an extension marker
732    /// (X.691 §17.3): a bit, then the string within the constraint, or a string of any
733    /// size.
734    pub fn octet_string_extensible(
735        &mut self,
736        lower: usize,
737        upper: usize,
738    ) -> Result<Octets<'a>, Error> {
739        match self.bit()? {
740            false => self.octet_string(lower, upper),
741            true => self.octets_in_fragments(),
742        }
743    }
744
745    /// The octets of an open type (X.691 §11.2): the complete encoding of a value,
746    /// after its length. The octets are borrowed, unless they are in fragments.
747    ///
748    /// A value that is decoded from an open type borrows from the input too, when it
749    /// is read from the octets that [`Octets::as_borrowed`] gives: they live as long as
750    /// the input. An open type of 16384 octets or more comes in fragments, which are
751    /// gathered: it owns its octets, and what is decoded from it is copied out.
752    ///
753    /// ```
754    /// use oxirush_aper::{Error, Octets, Reader};
755    ///
756    /// // The OCTET STRING (SIZE (0..255)) that an open type holds
757    /// fn held(input: &[u8]) -> Result<Octets<'_>, Error> {
758    ///     let open = Reader::new(input).open_type()?;
759    ///     match open.as_borrowed() {
760    ///         // In one piece: the string is a part of `input`
761    ///         Some(octets) => Reader::new(octets).octet_string(0, 255),
762    ///         // Gathered from fragments: the string is copied out of them
763    ///         None => Ok(Reader::new(&open).octet_string(0, 255)?.into_owned()),
764    ///     }
765    /// }
766    ///
767    /// let string = held(&[0x03, 0x02, 0xab, 0xcd])?;
768    /// assert_eq!(format!("{string:?}"), "abcd");
769    /// assert!(string.is_borrowed());
770    /// # Ok::<(), Error>(())
771    /// ```
772    #[inline]
773    pub fn open_type(&mut self) -> Result<Octets<'a>, Error> {
774        self.octets_in_fragments()
775    }
776
777    /// Octets after their unconstrained length: borrowed when they are in one piece.
778    #[inline]
779    fn octets_in_fragments(&mut self) -> Result<Octets<'a>, Error> {
780        let (count, more) = self.length()?;
781        let first = self.octets(count)?;
782        if !more {
783            return Ok(Octets::borrowed(first));
784        }
785        self.more_fragments(first).map(Octets::owned)
786    }
787
788    /// The octets of the fragments that follow `first`, after it.
789    #[cold]
790    fn more_fragments(&mut self, first: &[u8]) -> Result<Vec<u8>, Error> {
791        let mut gathered = first.to_vec();
792        let mut fragment = first.len();
793        loop {
794            let (count, more) = self.length_after(fragment)?;
795            gathered.extend_from_slice(self.octets(count)?);
796            if !more {
797                return Ok(gathered);
798            }
799            fragment = count;
800        }
801    }
802
803    /// Skip the open type of an extension addition: the complete encoding of a value
804    /// (X.691 §19.9, §11.2.1), which is one octet at least (§11.1.3.1).
805    fn skip_open_type(&mut self) -> Result<(), Error> {
806        let mut octets = 0;
807        let (mut count, mut more) = self.length()?;
808        loop {
809            self.octets(count)?;
810            octets += count;
811            if !more {
812                break;
813            }
814            (count, more) = self.length_after(count)?;
815        }
816        if octets == 0 {
817            return Err(Error::decode(
818                "an extension addition has no octet: an open type holds a complete encoding",
819            ));
820        }
821        Ok(())
822    }
823
824    // ── BIT STRING ──────────────────────────────────────────────────────────
825
826    /// A BIT STRING of 64 bits at most, of the size constraint `lower..=upper` (X.691
827    /// §16.9 to §16.11): a bit-field for one size of 16 bits at most, and octet-aligned
828    /// otherwise, after its length when its size varies.
829    #[inline]
830    pub fn bits_sized(&mut self, lower: usize, upper: usize) -> Result<Bits, Error> {
831        debug_assert!(lower <= upper && upper <= 64);
832        let size = self.size(lower, upper)?;
833        if size == 0 {
834            return Ok(Bits::EMPTY);
835        }
836        if lower != upper || size > 16 {
837            self.align();
838        }
839        Ok(Bits::low(self.bits(size)?, size))
840    }
841
842    /// A BIT STRING of the size constraint `lower..=upper` (X.691 §16), with
843    /// [`UNBOUNDED`] for no upper bound. The octets are borrowed where the string is
844    /// octet-aligned, and one of 64 bits at most is held without an allocation.
845    ///
846    /// A string of 16384 bits or more is in fragments when its size has no bound
847    /// below 64K, and is then copied.
848    #[inline]
849    pub fn bit_string(&mut self, lower: usize, upper: usize) -> Result<BitString<'a>, Error> {
850        if upper >= 65536 {
851            let bits = self.bit_string_in_fragments()?;
852            return check_size(bits.len(), lower, upper).map(|()| bits);
853        }
854        let size = self.size(lower, upper)?;
855        if size == 0 {
856            return Ok(BitString::default());
857        }
858        if lower == upper && size <= 16 {
859            return self.bit_field(size);
860        }
861        let octets = self.aligned_bits(size)?;
862        Ok(BitString::of(octets, size))
863    }
864
865    /// A BIT STRING whose size constraint `lower..=upper` has an extension marker
866    /// (X.691 §16.6): a bit, then the string within the constraint, or a string of any
867    /// size.
868    pub fn bit_string_extensible(
869        &mut self,
870        lower: usize,
871        upper: usize,
872    ) -> Result<BitString<'a>, Error> {
873        match self.bit()? {
874            false => self.bit_string(lower, upper),
875            true => self.bit_string_in_fragments(),
876        }
877    }
878
879    /// `count` bits that are not aligned, as a bit string.
880    fn bit_field(&mut self, count: usize) -> Result<BitString<'a>, Error> {
881        if count <= 64 {
882            return Ok(BitString::from(Bits::low(self.bits(count)?, count)));
883        }
884        let mut octets = Vec::with_capacity(count.div_ceil(8).min(self.remaining() / 8 + 1));
885        let mut left = count;
886        while left > 0 {
887            let part = left.min(8);
888            octets.push((self.bits(part)? << (8 - part)) as u8);
889            left -= part;
890        }
891        Ok(BitString::of(Octets::owned(octets), count))
892    }
893
894    /// A bit string after its unconstrained length, which counts bits: borrowed when
895    /// it is in one piece.
896    fn bit_string_in_fragments(&mut self) -> Result<BitString<'a>, Error> {
897        let (count, more) = self.length()?;
898        if !more {
899            let octets = self.aligned_bits(count)?;
900            return Ok(BitString::of(octets, count));
901        }
902        // A fragment is a multiple of 16384 bits, and so whole octets.
903        let mut gathered = self.octets(count / 8)?.to_vec();
904        let mut bits = count;
905        let mut fragment = count;
906        loop {
907            let (count, more) = self.length_after(fragment)?;
908            bits += count;
909            if more {
910                gathered.extend_from_slice(self.octets(count / 8)?);
911                fragment = count;
912            } else {
913                gathered.extend_from_slice(&self.aligned_bits(count)?);
914                return Ok(BitString::of(Octets::owned(gathered), bits));
915            }
916        }
917    }
918
919    // ── Character strings ───────────────────────────────────────────────────
920
921    /// A PrintableString of the size constraint `lower..=upper` (X.691 §30.5), with
922    /// [`UNBOUNDED`] for no upper bound: a character is eight bits in the aligned
923    /// variant.
924    pub fn printable_string(&mut self, lower: usize, upper: usize) -> Result<Cow<'a, str>, Error> {
925        self.known_multiplier(lower, upper, false, Alphabet::Printable)
926    }
927
928    /// A PrintableString whose size constraint has an extension marker (X.691 §30.4).
929    pub fn printable_string_extensible(
930        &mut self,
931        lower: usize,
932        upper: usize,
933    ) -> Result<Cow<'a, str>, Error> {
934        self.known_multiplier(lower, upper, true, Alphabet::Printable)
935    }
936
937    /// A VisibleString of the size constraint `lower..=upper`, with [`UNBOUNDED`] for
938    /// no upper bound.
939    pub fn visible_string(&mut self, lower: usize, upper: usize) -> Result<Cow<'a, str>, Error> {
940        self.known_multiplier(lower, upper, false, Alphabet::Visible)
941    }
942
943    /// A VisibleString whose size constraint has an extension marker.
944    pub fn visible_string_extensible(
945        &mut self,
946        lower: usize,
947        upper: usize,
948    ) -> Result<Cow<'a, str>, Error> {
949        self.known_multiplier(lower, upper, true, Alphabet::Visible)
950    }
951
952    /// An IA5String of the size constraint `lower..=upper`, with [`UNBOUNDED`] for no
953    /// upper bound.
954    pub fn ia5_string(&mut self, lower: usize, upper: usize) -> Result<Cow<'a, str>, Error> {
955        self.known_multiplier(lower, upper, false, Alphabet::Ia5)
956    }
957
958    /// An IA5String whose size constraint has an extension marker.
959    pub fn ia5_string_extensible(
960        &mut self,
961        lower: usize,
962        upper: usize,
963    ) -> Result<Cow<'a, str>, Error> {
964        self.known_multiplier(lower, upper, true, Alphabet::Ia5)
965    }
966
967    /// A UTF8String (X.691 §30.6): the length of its octets, then its octets. A size
968    /// constraint on it is not PER-visible (§10.3.7), and is not looked at.
969    pub fn utf8_string(&mut self) -> Result<Cow<'a, str>, Error> {
970        let octets = self.octets_in_fragments()?;
971        text(
972            octets,
973            |text| core::str::from_utf8(text).is_ok(),
974            "UTF8String",
975        )
976    }
977
978    /// A string of a known-multiplier type whose characters are eight bits.
979    fn known_multiplier(
980        &mut self,
981        lower: usize,
982        upper: usize,
983        extensible: bool,
984        alphabet: Alphabet,
985    ) -> Result<Cow<'a, str>, Error> {
986        let within = |octets: &[u8]| octets.iter().all(|octet| alphabet.has(*octet));
987        // Outside the root, the string is encoded as one without a size constraint.
988        let (lower, upper) = match extensible && self.bit()? {
989            true => (0, UNBOUNDED),
990            false => (lower, upper),
991        };
992        if upper >= 65536 {
993            let octets = self.octets_in_fragments()?;
994            check_size(octets.len(), lower, upper)?;
995            return text(octets, within, alphabet.name());
996        }
997        let size = self.size(lower, upper)?;
998        // One size of two characters at most, and a size that varies up to one
999        // character, are bit-fields (X.691 §30.5.6, §30.5.7).
1000        let aligned = if lower == upper {
1001            upper * 8 > 16
1002        } else {
1003            upper * 8 >= 16
1004        };
1005        let octets = match (size, aligned) {
1006            (0, _) => Octets::EMPTY,
1007            (_, true) => Octets::borrowed(self.octets(size)?),
1008            (_, false) => {
1009                let short = self.bits(size * 8)?.to_be_bytes();
1010                Octets::owned(short[8 - size..].to_vec())
1011            }
1012        };
1013        text(octets, within, alphabet.name())
1014    }
1015
1016    // ── OBJECT IDENTIFIER ───────────────────────────────────────────────────
1017
1018    /// An OBJECT IDENTIFIER (X.691 §24): the length of its contents octets, then the
1019    /// contents octets that the Basic Encoding Rules give it.
1020    pub fn object_identifier(&mut self) -> Result<ObjectIdentifier, Error> {
1021        let octets = self.octets_in_fragments()?;
1022        if self.noting {
1023            // The first octet of each arc, where the octets before it end an arc.
1024            let start = self.at - octets.len() * 8;
1025            let mut first = true;
1026            for (at, octet) in octets.iter().enumerate() {
1027                if first && *octet == 0x80 {
1028                    self.note(Fault::LongArc, start + at * 8);
1029                }
1030                first = octet & 0x80 == 0;
1031            }
1032        }
1033        ObjectIdentifier::from_contents(&octets)
1034    }
1035
1036    // ── SEQUENCE OF ─────────────────────────────────────────────────────────
1037
1038    /// An empty list that has room for `count` elements, as far as the octets that
1039    /// are left may hold them: a count that a peer claims reserves little.
1040    #[inline]
1041    pub fn list<T>(&self, count: usize) -> Vec<T> {
1042        let most = RESERVED / size_of::<T>().max(1);
1043        Vec::with_capacity(count.min(most.max(1)).min(self.remaining() + 1))
1044    }
1045}
1046
1047/// The extension additions of a SEQUENCE that a reader was given: which of them are
1048/// present, in their order. [`Reader::additions`] gives it, and has an example.
1049#[derive(Clone, Debug)]
1050pub struct Additions<'a> {
1051    bitmap: BitString<'a>,
1052    next: usize,
1053}
1054
1055impl Additions<'_> {
1056    /// Whether the next addition is present: the first one at the first call. An
1057    /// addition that the encoding does not count is not present.
1058    pub fn present(&mut self) -> bool {
1059        let present = self.bitmap.get(self.next).unwrap_or(false);
1060        self.next += 1;
1061        present
1062    }
1063
1064    /// Skip the additions that are present and were not asked for: those that a later
1065    /// version of the specification adds.
1066    pub fn skip_rest(self, reader: &mut Reader<'_>) -> Result<(), Error> {
1067        for position in self.next..self.bitmap.len() {
1068            if self.bitmap.get(position) == Some(true) {
1069                reader.skip_open_type()?;
1070            }
1071        }
1072        Ok(())
1073    }
1074}
1075
1076/// The known-multiplier character string types whose characters are eight bits in the
1077/// aligned variant, each with the characters that it has.
1078#[derive(Clone, Copy)]
1079pub(crate) enum Alphabet {
1080    Printable,
1081    Visible,
1082    Ia5,
1083}
1084
1085impl Alphabet {
1086    /// Whether the type has the character of a code (ITU-T X.680 (02/2021) §41.4).
1087    pub(crate) fn has(self, code: u8) -> bool {
1088        match self {
1089            Self::Printable => code.is_ascii_alphanumeric() || b" '()+,-./:=?".contains(&code),
1090            Self::Visible => (0x20..=0x7e).contains(&code),
1091            Self::Ia5 => code <= 0x7f,
1092        }
1093    }
1094
1095    pub(crate) fn name(self) -> &'static str {
1096        match self {
1097            Self::Printable => "PrintableString",
1098            Self::Visible => "VisibleString",
1099            Self::Ia5 => "IA5String",
1100        }
1101    }
1102}
1103
1104/// The text that octets are, when `valid` says that they are a string of the type
1105/// `name`.
1106fn text<'a>(
1107    octets: Octets<'a>,
1108    valid: impl Fn(&[u8]) -> bool,
1109    name: &str,
1110) -> Result<Cow<'a, str>, Error> {
1111    let not_text = || Error::decode(alloc::format!("a character string is no {name}"));
1112    if !valid(&octets) {
1113        return Err(not_text());
1114    }
1115    // What is valid is ASCII, or was checked as UTF-8.
1116    match octets.as_borrowed() {
1117        Some(borrowed) => match core::str::from_utf8(borrowed) {
1118            Ok(text) => Ok(Cow::Borrowed(text)),
1119            Err(_) => Err(not_text()),
1120        },
1121        None => match String::from_utf8(octets.into_vec()) {
1122            Ok(text) => Ok(Cow::Owned(text)),
1123            Err(_) => Err(not_text()),
1124        },
1125    }
1126}
1127
1128/// The error of an index that nothing has: among the additions when it is one of an
1129/// `addition`.
1130#[cold]
1131fn no_index(index: u64, addition: bool, of: &str) -> Error {
1132    Error::decode(match addition {
1133        false => alloc::format!("{index} is no {of}"),
1134        true => alloc::format!("{index} is no {of} among those after its extension marker"),
1135    })
1136}
1137
1138/// A size that was read after an unconstrained length is within `lower..=upper`.
1139fn check_size(size: usize, lower: usize, upper: usize) -> Result<(), Error> {
1140    if (lower..=upper).contains(&size) {
1141        return Ok(());
1142    }
1143    let upper = (upper != UNBOUNDED).then_some(upper);
1144    Err(Error::size_read_outside(size, lower, upper))
1145}
1146
1147/// The error of a value that octets follow.
1148#[cold]
1149fn followed(octets: usize) -> Error {
1150    Error::decode(match octets {
1151        1 => String::from("the value is followed by 1 octet"),
1152        octets => alloc::format!("the value is followed by {octets} octets"),
1153    })
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158    use super::Reader;
1159    use alloc::string::ToString;
1160
1161    /// The review of the release candidate found that the octets after the most that a
1162    /// reader takes, 512 MiB of them on 32 bits, were never refused: they follow the
1163    /// value, as any other octets after it do.
1164    #[test]
1165    fn the_octets_after_those_that_a_reader_takes_follow_the_value() {
1166        let octets = [0x05, 0x00, 0x00];
1167        let mut reader = Reader::taking(&octets, 1);
1168        assert_eq!(reader.unsigned(0, 255).unwrap(), 5);
1169        assert!(reader.unsigned(0, 255).is_err());
1170        let error = reader.finish().unwrap_err().to_string();
1171        assert!(error.contains("followed by 2 octets"), "{error}");
1172        let mut reader = Reader::taking(&octets[..1], 1);
1173        assert_eq!(reader.unsigned(0, 255).unwrap(), 5);
1174        assert!(reader.finish().is_ok());
1175    }
1176}