rasn/per/
de.rs

1use alloc::{collections::VecDeque, string::ToString, vec::Vec};
2use bitvec::field::BitField;
3
4use super::{FOURTY_EIGHT_K, SIXTEEN_K, SIXTY_FOUR_K, THIRTY_TWO_K};
5use crate::bits::{to_left_padded_vec, to_vec};
6use crate::{
7    de::Error as _,
8    types::{
9        self,
10        constraints::{self, Extensible},
11        fields::{Field, Fields},
12        strings::{should_be_indexed, StaticPermittedAlphabet},
13        Constraints, Enumerated, Tag,
14    },
15    Decode,
16};
17
18pub use crate::error::DecodeError;
19pub type Result<T, E = DecodeError> = core::result::Result<T, E>;
20
21type InputSlice<'input> = nom_bitvec::BSlice<'input, u8, bitvec::order::Msb0>;
22
23#[derive(Clone, Copy, Debug)]
24pub struct DecoderOptions {
25    #[allow(unused)]
26    aligned: bool,
27}
28
29impl DecoderOptions {
30    pub fn aligned() -> Self {
31        Self { aligned: true }
32    }
33
34    pub fn unaligned() -> Self {
35        Self { aligned: false }
36    }
37    #[must_use]
38    fn current_codec(self) -> crate::Codec {
39        if self.aligned {
40            crate::Codec::Aper
41        } else {
42            crate::Codec::Uper
43        }
44    }
45}
46
47pub struct Decoder<'input> {
48    input: InputSlice<'input>,
49    options: DecoderOptions,
50    /// When the decoder contains fields, we check against optional or default
51    /// fields to know the presence of those fields.
52    fields: VecDeque<(Field, bool)>,
53    extension_fields: Option<Fields>,
54    extensions_present: Option<Option<VecDeque<(Field, bool)>>>,
55}
56
57impl<'input> Decoder<'input> {
58    pub fn codec(&self) -> crate::Codec {
59        self.options.current_codec()
60    }
61    pub fn new(input: &'input crate::types::BitStr, options: DecoderOptions) -> Self {
62        Self {
63            input: input.into(),
64            options,
65            fields: <_>::default(),
66            extension_fields: <_>::default(),
67            extensions_present: <_>::default(),
68        }
69    }
70
71    /// Returns the remaining input, if any.
72    pub fn input(&self) -> &'input crate::types::BitStr {
73        self.input.0
74    }
75
76    #[track_caller]
77    fn require_field(&mut self, tag: Tag) -> Result<bool> {
78        if self
79            .fields
80            .front()
81            .map(|field| field.0.tag_tree.smallest_tag() == tag)
82            .unwrap_or_default()
83        {
84            Ok(self.fields.pop_front().unwrap().1)
85        } else {
86            Err(DecodeError::missing_tag_class_or_value_in_sequence_or_set(
87                tag.class,
88                tag.value,
89                self.codec(),
90            ))
91        }
92    }
93
94    fn parse_extensible_bit(&mut self, constraints: &Constraints) -> Result<bool> {
95        constraints
96            .extensible()
97            .then(|| self.parse_one_bit())
98            .transpose()
99            .map(|opt| opt.unwrap_or_default())
100    }
101
102    fn extension_is_present(&mut self) -> Result<Option<(Field, bool)>> {
103        let codec = self.codec();
104        Ok(self
105            .extensions_present
106            .as_mut()
107            .ok_or_else(|| DecodeError::type_not_extensible(codec))?
108            .as_mut()
109            .ok_or_else(|| DecodeError::type_not_extensible(codec))?
110            .pop_front())
111    }
112
113    fn parse_padding(&self, input: InputSlice<'input>) -> Result<InputSlice<'input>> {
114        if !self.options.aligned {
115            Ok(input)
116        } else {
117            self.force_parse_padding(input)
118        }
119    }
120
121    fn force_parse_padding(&self, input: InputSlice<'input>) -> Result<InputSlice<'input>> {
122        if input.len() % 8 == 0 {
123            Ok(input)
124        } else {
125            let (input, _) = nom::bytes::streaming::take(input.len() % 8)(input)
126                .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
127            Ok(input)
128        }
129    }
130
131    fn parse_optional_and_default_field_bitmap(
132        &mut self,
133        fields: &Fields,
134    ) -> Result<InputSlice<'input>> {
135        let (input, bitset) =
136            nom::bytes::streaming::take(fields.number_of_optional_and_default_fields())(self.input)
137                .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
138
139        self.input = input;
140        Ok(bitset)
141    }
142
143    fn decode_extensible_string(
144        &mut self,
145        constraints: Constraints,
146        is_large_string: bool,
147        mut decode_fn: impl FnMut(InputSlice<'input>, usize) -> Result<InputSlice<'input>>,
148    ) -> Result<()> {
149        let extensible_is_present = self.parse_extensible_bit(&constraints)?;
150        let constraints = constraints.size().filter(|_| !extensible_is_present);
151        let input =
152            self.decode_string_length(self.input, constraints, is_large_string, &mut decode_fn)?;
153        self.input = input;
154        Ok(())
155    }
156
157    fn decode_extensible_container(
158        &mut self,
159        constraints: Constraints,
160        mut decode_fn: impl FnMut(InputSlice<'input>, usize) -> Result<InputSlice<'input>>,
161    ) -> Result<()> {
162        let extensible_is_present = self.parse_extensible_bit(&constraints)?;
163        let constraints = constraints.size().filter(|_| !extensible_is_present);
164        let input = self.decode_length(self.input, constraints, &mut decode_fn)?;
165        self.input = input;
166        Ok(())
167    }
168
169    fn decode_octets(&mut self) -> Result<types::BitString> {
170        let mut buffer = types::BitString::default();
171        let codec = self.codec();
172
173        let input = self.decode_length(self.input, <_>::default(), &mut |input, length| {
174            let (input, data) = nom::bytes::streaming::take(length * 8)(input)
175                .map_err(|e| DecodeError::map_nom_err(e, codec))?;
176            buffer.extend(&*data);
177            Ok(input)
178        })?;
179
180        self.input = input;
181        Ok(buffer)
182    }
183
184    fn decode_unknown_length(
185        &mut self,
186        mut input: InputSlice<'input>,
187        decode_fn: &mut impl FnMut(InputSlice<'input>, usize) -> Result<InputSlice<'input>>,
188    ) -> Result<InputSlice<'input>> {
189        input = self.parse_padding(input)?;
190        let (input, mask) = nom::bytes::streaming::take(1u8)(input)
191            .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
192
193        if !mask[0] {
194            let (input, length) = nom::bytes::streaming::take(7u8)(input)
195                .map(|(i, bs)| (i, bs.to_bitvec()))
196                .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
197            (decode_fn)(input, length.load_be::<usize>())
198        } else {
199            let (input, mask) = nom::bytes::streaming::take(1u8)(input)
200                .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
201
202            if !mask[0] {
203                let (input, length) = nom::bytes::streaming::take(14u8)(input)
204                    .map(|(i, bs)| (i, bs.to_bitvec()))
205                    .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
206                (decode_fn)(input, length.load_be::<usize>())
207            } else {
208                let (input, mask) = nom::bytes::streaming::take(6u8)(input)
209                    .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
210                let length: usize = match mask.load_be::<u8>() {
211                    1 => SIXTEEN_K.into(),
212                    2 => THIRTY_TWO_K.into(),
213                    3 => FOURTY_EIGHT_K.into(),
214                    4 => SIXTY_FOUR_K as usize,
215                    _ => {
216                        return Err(DecodeError::parser_fail(
217                            "Invalid length fragment".into(),
218                            self.codec(),
219                        ));
220                    }
221                };
222
223                let mut input = (decode_fn)(input, length)?;
224
225                loop {
226                    let new_input = self.decode_length(input, <_>::default(), decode_fn)?;
227
228                    if input.len() == new_input.len() || new_input.is_empty() {
229                        break;
230                    } else {
231                        input = (decode_fn)(new_input, length)?;
232                    }
233                }
234
235                Ok(input)
236            }
237        }
238    }
239
240    pub fn decode_string_length(
241        &mut self,
242        mut input: InputSlice<'input>,
243        constraints: Option<&Extensible<constraints::Size>>,
244        is_large_string: bool,
245        decode_fn: &mut impl FnMut(InputSlice<'input>, usize) -> Result<InputSlice<'input>>,
246    ) -> Result<InputSlice<'input>> {
247        let Some(constraints) = constraints else {
248            return self.decode_unknown_length(input, decode_fn);
249        };
250
251        let size_constraint = constraints.constraint;
252        if let Some(range) = size_constraint
253            .range()
254            .filter(|range| *range <= u16::MAX.into())
255        {
256            if range == 0 {
257                Ok(input)
258            } else if range == 1 {
259                if self.options.aligned {
260                    input = self.parse_padding(input)?;
261                }
262                (decode_fn)(input, size_constraint.minimum())
263            } else {
264                let range = if self.options.aligned && range > 256 {
265                    input = self.parse_padding(input)?;
266                    let range = crate::num::log2(range as i128);
267                    crate::bits::range_from_len(
268                        range
269                            .is_power_of_two()
270                            .then_some(range)
271                            .unwrap_or_else(|| range.next_power_of_two()),
272                    )
273                } else {
274                    range as i128
275                };
276
277                let (mut input, length) =
278                    nom::bytes::streaming::take(crate::num::log2(range))(input)
279                        .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
280                if is_large_string {
281                    input = self.parse_padding(input)?;
282                }
283                length
284                    .load_be::<usize>()
285                    .checked_add(size_constraint.minimum())
286                    .ok_or_else(|| DecodeError::exceeds_max_length(usize::MAX.into(), self.codec()))
287                    .and_then(|sum| (decode_fn)(input, sum))
288            }
289        } else {
290            self.decode_unknown_length(input, decode_fn)
291        }
292    }
293
294    pub fn decode_length(
295        &mut self,
296        mut input: InputSlice<'input>,
297        constraints: Option<&Extensible<constraints::Size>>,
298        decode_fn: &mut impl FnMut(InputSlice<'input>, usize) -> Result<InputSlice<'input>>,
299    ) -> Result<InputSlice<'input>> {
300        let Some(constraints) = constraints else {
301            return self.decode_unknown_length(input, decode_fn);
302        };
303
304        let size_constraint = constraints.constraint;
305        if let Some(range) = size_constraint
306            .range()
307            .filter(|range| *range <= u16::MAX.into())
308        {
309            if range == 0 {
310                Ok(input)
311            } else if range == 1 {
312                (decode_fn)(input, size_constraint.minimum())
313            } else {
314                let range = if self.options.aligned && range > 256 {
315                    input = self.parse_padding(input)?;
316                    let range = crate::num::log2(range as i128);
317                    crate::bits::range_from_len(
318                        range
319                            .is_power_of_two()
320                            .then_some(range)
321                            .unwrap_or_else(|| range.next_power_of_two()),
322                    )
323                } else {
324                    range as i128
325                };
326
327                let (mut input, length) =
328                    nom::bytes::streaming::take(crate::num::log2(range))(input)
329                        .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
330                input = self.parse_padding(input)?;
331                length
332                    .load_be::<usize>()
333                    .checked_add(size_constraint.minimum())
334                    .ok_or_else(|| DecodeError::exceeds_max_length(usize::MAX.into(), self.codec()))
335                    .and_then(|sum| (decode_fn)(input, sum))
336            }
337        } else {
338            self.decode_unknown_length(input, decode_fn)
339        }
340    }
341
342    fn parse_one_bit(&mut self) -> Result<bool> {
343        let (input, boolean) = nom::bytes::streaming::take(1u8)(self.input)
344            .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
345        self.input = input;
346        Ok(boolean[0])
347    }
348
349    fn parse_normally_small_integer(&mut self) -> Result<types::Integer> {
350        let is_large = self.parse_one_bit()?;
351        let constraints = if is_large {
352            constraints::Value::new(constraints::Bounded::start_from(0)).into()
353        } else {
354            constraints::Value::new(constraints::Bounded::new(0, 63)).into()
355        };
356
357        self.parse_integer(Constraints::new(&[constraints]))
358    }
359
360    fn parse_non_negative_binary_integer<I: types::IntegerType>(
361        &mut self,
362        range: i128,
363    ) -> Result<I> {
364        let bits = crate::num::log2(range);
365        let (input, data) = nom::bytes::streaming::take(bits)(self.input)
366            .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
367        self.input = input;
368        let data = if data.len() < 8 {
369            let mut buffer = types::BitString::repeat(false, 8 - data.len());
370            buffer.extend_from_bitslice(&data);
371            buffer
372        } else {
373            data.to_bitvec()
374        };
375
376        I::try_from_unsigned_bytes(&to_left_padded_vec(&data), self.codec())
377    }
378
379    fn parse_integer<I: types::IntegerType>(&mut self, constraints: Constraints) -> Result<I> {
380        let extensible = self.parse_extensible_bit(&constraints)?;
381        let value_constraint = constraints.value();
382
383        let Some(value_constraint) = value_constraint.filter(|_| !extensible) else {
384            let bytes = to_vec(&self.decode_octets()?);
385            return I::try_from_bytes(&bytes, self.codec());
386        };
387
388        const K64: i128 = SIXTY_FOUR_K as i128;
389        const OVER_K64: i128 = K64 + 1;
390
391        let number = if let Some(range) = value_constraint.constraint.range() {
392            match (self.options.aligned, range) {
393                (_, 0) => {
394                    return value_constraint
395                        .constraint
396                        .minimum()
397                        .try_into()
398                        .map_err(|_| DecodeError::integer_overflow(I::WIDTH, self.codec()))
399                }
400                (true, 256) => {
401                    self.input = self.parse_padding(self.input)?;
402                    self.parse_non_negative_binary_integer(range)?
403                }
404                (true, 257..=K64) => {
405                    self.input = self.parse_padding(self.input)?;
406                    self.parse_non_negative_binary_integer(K64)?
407                }
408                (true, OVER_K64..) => {
409                    let range_len_in_bytes =
410                        num_integer::div_ceil(crate::num::log2(range), 8) as i128;
411                    let length: u32 = self.parse_non_negative_binary_integer(range_len_in_bytes)?;
412                    self.input = self.parse_padding(self.input)?;
413                    let range = length
414                        .checked_add(1)
415                        .ok_or_else(|| {
416                            DecodeError::exceeds_max_length(u32::MAX.into(), self.codec())
417                        })?
418                        .checked_mul(8)
419                        .ok_or_else(|| {
420                            DecodeError::exceeds_max_length(u32::MAX.into(), self.codec())
421                        })?;
422                    self.parse_non_negative_binary_integer(crate::bits::range_from_len(range))?
423                }
424                (_, _) => self.parse_non_negative_binary_integer(range)?,
425            }
426        } else {
427            let bytes = to_vec(&self.decode_octets()?);
428
429            value_constraint
430                .constraint
431                .as_start()
432                .map(|_| I::try_from_unsigned_bytes(&bytes, self.codec()))
433                .unwrap_or_else(|| I::try_from_signed_bytes(&bytes, self.codec()))?
434        };
435
436        let minimum: I = value_constraint
437            .constraint
438            .minimum()
439            .try_into()
440            .map_err(|_| DecodeError::integer_overflow(I::WIDTH, self.codec()))?;
441
442        Ok(minimum.wrapping_add(number))
443    }
444
445    fn parse_extension_header(&mut self) -> Result<bool> {
446        match self.extensions_present {
447            Some(Some(_)) => return Ok(true),
448            Some(None) => (),
449            None => return Ok(false),
450        }
451
452        // The length bitfield has a lower bound of `1..`
453        let extensions_length = self.parse_normally_small_integer()? + 1;
454        let (input, bitfield) =
455            nom::bytes::streaming::take(usize::try_from(extensions_length).map_err(
456                |e: num_bigint::TryFromBigIntError<types::Integer>| {
457                    DecodeError::integer_type_conversion_failed(e.to_string(), self.codec())
458                },
459            )?)(self.input)
460            .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
461        self.input = input;
462
463        let extensions_present: VecDeque<_> = self
464            .extension_fields
465            .as_ref()
466            .unwrap()
467            .iter()
468            .zip(bitfield.iter().map(|b| *b))
469            .collect();
470
471        for (field, is_present) in &extensions_present {
472            if field.is_not_optional_or_default() && !is_present {
473                return Err(DecodeError::required_extension_not_present(
474                    field.tag,
475                    self.codec(),
476                ));
477            }
478        }
479
480        self.extensions_present = Some(Some(extensions_present));
481
482        Ok(true)
483    }
484
485    #[allow(clippy::too_many_lines)]
486    fn parse_fixed_width_string<ALPHABET: StaticPermittedAlphabet>(
487        &mut self,
488        constraints: Constraints,
489    ) -> Result<ALPHABET> {
490        use crate::types::constraints::Bounded;
491
492        let mut bit_string = types::BitString::default();
493        let char_width = constraints
494            .permitted_alphabet()
495            .map(|alphabet| crate::num::log2(alphabet.constraint.len() as i128) as usize)
496            .unwrap_or(ALPHABET::character_width() as usize);
497
498        let char_width = (self.options.aligned && !char_width.is_power_of_two())
499            .then(|| char_width.next_power_of_two())
500            .unwrap_or(char_width);
501
502        let is_large_string = if let Some(size) = constraints.size() {
503            match *size.constraint {
504                Bounded::Range {
505                    start: Some(_),
506                    end: Some(_),
507                } if size
508                    .constraint
509                    .range()
510                    .unwrap()
511                    .checked_mul(char_width)
512                    .ok_or_else(|| {
513                        DecodeError::exceeds_max_length(usize::MAX.into(), self.codec())
514                    })?
515                    > 16 =>
516                {
517                    true
518                }
519                Bounded::Single(max)
520                    if max.checked_mul(char_width).ok_or_else(|| {
521                        DecodeError::exceeds_max_length(usize::MAX.into(), self.codec())
522                    })? > 16 =>
523                {
524                    self.input = self.parse_padding(self.input)?;
525                    true
526                }
527                Bounded::Range {
528                    start: None,
529                    end: Some(max),
530                } if max.checked_mul(char_width).ok_or_else(|| {
531                    DecodeError::exceeds_max_length(usize::MAX.into(), self.codec())
532                })? > 16 =>
533                {
534                    self.input = self.parse_padding(self.input)?;
535                    true
536                }
537                _ => false,
538            }
539        } else {
540            false
541        };
542
543        let mut total_length = 0;
544        let codec = self.codec();
545        self.decode_extensible_string(constraints.clone(), is_large_string, |input, length| {
546            total_length += length;
547            if constraints
548                .permitted_alphabet()
549                .map_or(false, |alphabet| alphabet.constraint.len() == 1)
550            {
551                return Ok(input);
552            }
553
554            let (input, part) = nom::bytes::streaming::take(length * char_width)(input)
555                .map_err(|e| DecodeError::map_nom_err(e, codec))?;
556            bit_string.extend(&*part);
557            Ok(input)
558        })?;
559
560        match (
561            constraints.permitted_alphabet(),
562            should_be_indexed(ALPHABET::CHARACTER_WIDTH, ALPHABET::CHARACTER_SET),
563            constraints.permitted_alphabet().map(|alphabet| {
564                ALPHABET::CHARACTER_WIDTH
565                    > self
566                        .options
567                        .aligned
568                        .then(|| {
569                            let alphabet_width =
570                                crate::num::log2(alphabet.constraint.len() as i128);
571                            alphabet_width
572                                .is_power_of_two()
573                                .then_some(alphabet_width)
574                                .unwrap_or_else(|| alphabet_width.next_power_of_two())
575                        })
576                        .unwrap_or(crate::num::log2(alphabet.constraint.len() as i128))
577            }),
578        ) {
579            (Some(alphabet), true, _) | (Some(alphabet), _, Some(true)) => {
580                if alphabet.constraint.len() == 1 {
581                    let mut string = ALPHABET::default();
582                    for _ in 0..total_length {
583                        string.push_char(alphabet.constraint[0]);
584                    }
585                    Ok(string)
586                } else {
587                    let map = alphabet
588                        .constraint
589                        .iter()
590                        .copied()
591                        .enumerate()
592                        .map(|(i, e)| (i as u32, e))
593                        .collect();
594                    ALPHABET::try_from_permitted_alphabet(&bit_string, Some(&map)).map_err(|e| {
595                        DecodeError::alphabet_constraint_not_satisfied(e, self.codec())
596                    })
597                }
598            }
599            (None, true, _) => ALPHABET::try_from_permitted_alphabet(&bit_string, None)
600                .map_err(|e| DecodeError::alphabet_constraint_not_satisfied(e, self.codec())),
601            (None, false, _) if !self.options.aligned => {
602                ALPHABET::try_from_permitted_alphabet(&bit_string, None)
603                    .map_err(|e| DecodeError::alphabet_constraint_not_satisfied(e, self.codec()))
604            }
605            _ => ALPHABET::try_from_bits(
606                bit_string,
607                self.options
608                    .aligned
609                    .then(|| {
610                        ALPHABET::CHARACTER_WIDTH
611                            .is_power_of_two()
612                            .then_some(ALPHABET::CHARACTER_WIDTH)
613                            .unwrap_or_else(|| ALPHABET::CHARACTER_WIDTH.next_power_of_two())
614                    })
615                    .unwrap_or(ALPHABET::CHARACTER_WIDTH) as usize,
616            )
617            .map_err(|e| DecodeError::alphabet_constraint_not_satisfied(e, self.codec())),
618        }
619    }
620}
621
622impl<'input> crate::Decoder for Decoder<'input> {
623    type Error = DecodeError;
624
625    fn codec(&self) -> crate::Codec {
626        Self::codec(self)
627    }
628    fn decode_any(&mut self) -> Result<types::Any> {
629        let mut octet_string = types::BitString::default();
630        let codec = self.codec();
631
632        self.decode_extensible_container(<_>::default(), |input, length| {
633            let (input, part) = nom::bytes::streaming::take(length * 8)(input)
634                .map_err(|e| DecodeError::map_nom_err(e, codec))?;
635            octet_string.extend(&*part);
636            Ok(input)
637        })?;
638
639        Ok(types::Any::new(to_vec(&octet_string)))
640    }
641
642    fn decode_bool(&mut self, _: Tag) -> Result<bool> {
643        self.parse_one_bit()
644    }
645
646    fn decode_enumerated<E: Enumerated>(&mut self, _: Tag) -> Result<E> {
647        let extensible = E::EXTENDED_VARIANTS
648            .is_some()
649            .then(|| self.parse_one_bit())
650            .transpose()?
651            .unwrap_or_default();
652
653        if extensible {
654            let index: usize = self.parse_normally_small_integer()?.try_into().map_err(
655                |e: num_bigint::TryFromBigIntError<types::Integer>| {
656                    DecodeError::integer_type_conversion_failed(e.to_string(), self.codec())
657                },
658            )?;
659            E::from_extended_enumeration_index(index)
660                .ok_or_else(|| DecodeError::enumeration_index_not_found(index, true, self.codec()))
661        } else {
662            let index = self.parse_non_negative_binary_integer::<usize>(E::variance() as i128)?;
663            E::from_enumeration_index(index)
664                .ok_or_else(|| DecodeError::enumeration_index_not_found(index, false, self.codec()))
665        }
666    }
667
668    fn decode_integer<I: types::IntegerType>(
669        &mut self,
670        _: Tag,
671        constraints: Constraints,
672    ) -> Result<I> {
673        self.parse_integer::<I>(constraints)
674    }
675
676    fn decode_octet_string(&mut self, _: Tag, constraints: Constraints) -> Result<Vec<u8>> {
677        let mut octet_string = types::BitString::default();
678        let codec = self.codec();
679
680        self.decode_extensible_container(constraints, |input, length| {
681            let (input, part) = nom::bytes::streaming::take(length * 8)(input)
682                .map_err(|e| DecodeError::map_nom_err(e, codec))?;
683
684            octet_string.extend(&*part);
685            Ok(input)
686        })?;
687
688        Ok(octet_string.into_vec())
689    }
690
691    fn decode_null(&mut self, _: Tag) -> Result<()> {
692        Ok(())
693    }
694
695    fn decode_object_identifier(&mut self, _: Tag) -> Result<crate::types::ObjectIdentifier> {
696        let octets = self.decode_octets()?.into_vec();
697        let decoder = crate::ber::de::Decoder::new(&octets, crate::ber::de::DecoderOptions::ber());
698        decoder.decode_object_identifier_from_bytes(&octets)
699    }
700
701    fn decode_bit_string(&mut self, _: Tag, constraints: Constraints) -> Result<types::BitString> {
702        let mut bit_string = types::BitString::default();
703        let codec = self.codec();
704
705        self.decode_extensible_container(constraints, |input, length| {
706            let (input, part) = nom::bytes::streaming::take(length)(input)
707                .map_err(|e| DecodeError::map_nom_err(e, codec))?;
708            bit_string.extend(&*part);
709            Ok(input)
710        })?;
711
712        Ok(bit_string)
713    }
714
715    fn decode_visible_string(
716        &mut self,
717        _: Tag,
718        constraints: Constraints,
719    ) -> Result<types::VisibleString> {
720        self.parse_fixed_width_string(constraints)
721    }
722
723    fn decode_ia5_string(&mut self, _: Tag, constraints: Constraints) -> Result<types::Ia5String> {
724        self.parse_fixed_width_string(constraints)
725    }
726
727    fn decode_printable_string(
728        &mut self,
729        _: Tag,
730        constraints: Constraints,
731    ) -> Result<types::PrintableString> {
732        self.parse_fixed_width_string(constraints)
733    }
734
735    fn decode_numeric_string(
736        &mut self,
737        _: Tag,
738        constraints: Constraints,
739    ) -> Result<types::NumericString> {
740        self.parse_fixed_width_string(constraints)
741    }
742
743    fn decode_teletex_string(
744        &mut self,
745        _: Tag,
746        _constraints: Constraints,
747    ) -> Result<types::TeletexString> {
748        todo!()
749    }
750
751    fn decode_bmp_string(&mut self, _: Tag, _constraints: Constraints) -> Result<types::BmpString> {
752        todo!()
753    }
754
755    fn decode_utf8_string(
756        &mut self,
757        tag: Tag,
758        constraints: Constraints,
759    ) -> Result<types::Utf8String> {
760        self.decode_octet_string(tag, constraints)
761            .and_then(|bytes| {
762                alloc::string::String::from_utf8(bytes).map_err(|e| {
763                    DecodeError::string_conversion_failed(
764                        Tag::UTF8_STRING,
765                        e.to_string(),
766                        self.codec(),
767                    )
768                })
769            })
770    }
771
772    fn decode_general_string(
773        &mut self,
774        tag: Tag,
775        constraints: Constraints,
776    ) -> Result<types::GeneralString> {
777        <types::GeneralString>::try_from(self.decode_octet_string(tag, constraints)?).map_err(|e| {
778            DecodeError::string_conversion_failed(Tag::GENERAL_STRING, e.to_string(), self.codec())
779        })
780    }
781
782    fn decode_generalized_time(&mut self, tag: Tag) -> Result<types::GeneralizedTime> {
783        let bytes = self.decode_octet_string(tag, <_>::default())?;
784
785        crate::ber::decode(&bytes)
786    }
787
788    fn decode_utc_time(&mut self, tag: Tag) -> Result<types::UtcTime> {
789        let bytes = self.decode_octet_string(tag, <_>::default())?;
790
791        crate::ber::decode(&bytes)
792    }
793
794    fn decode_sequence_of<D: Decode>(
795        &mut self,
796        _: Tag,
797        constraints: Constraints,
798    ) -> Result<Vec<D>, Self::Error> {
799        let mut sequence_of = Vec::new();
800        let options = self.options;
801        self.decode_extensible_container(constraints, |mut input, length| {
802            sequence_of.append(
803                &mut (0..length)
804                    .map(|_| {
805                        let mut decoder = Self::new(input.0, options);
806                        let value = D::decode(&mut decoder)?;
807                        input = decoder.input;
808                        Ok(value)
809                    })
810                    .collect::<Result<Vec<_>>>()?,
811            );
812
813            Ok(input)
814        })?;
815
816        Ok(sequence_of)
817    }
818
819    fn decode_set_of<D: Decode + Ord>(
820        &mut self,
821        tag: Tag,
822        constraints: Constraints,
823    ) -> Result<types::SetOf<D>, Self::Error> {
824        self.decode_sequence_of(tag, constraints)
825            .map(|seq| seq.into_iter().collect())
826    }
827
828    fn decode_sequence<D, DF, F>(
829        &mut self,
830        _: Tag,
831        _: Option<DF>,
832        decode_fn: F,
833    ) -> Result<D, Self::Error>
834    where
835        D: crate::types::Constructed,
836        DF: FnOnce() -> D,
837        F: FnOnce(&mut Self) -> Result<D, Self::Error>,
838    {
839        let is_extensible = D::EXTENDED_FIELDS
840            .is_some()
841            .then(|| self.parse_one_bit())
842            .transpose()?
843            .unwrap_or_default();
844        let bitmap = self.parse_optional_and_default_field_bitmap(&D::FIELDS)?;
845
846        let value = {
847            let mut sequence_decoder = Self::new(self.input(), self.options);
848            sequence_decoder.extension_fields = D::EXTENDED_FIELDS;
849            sequence_decoder.extensions_present = is_extensible.then_some(None);
850            sequence_decoder.fields = D::FIELDS
851                .optional_and_default_fields()
852                .zip(bitmap.into_iter().map(|b| *b))
853                .collect();
854            let value = (decode_fn)(&mut sequence_decoder)?;
855
856            self.input = sequence_decoder.input;
857            value
858        };
859
860        Ok(value)
861    }
862
863    fn decode_explicit_prefix<D: Decode>(&mut self, _: Tag) -> Result<D> {
864        D::decode(self)
865    }
866
867    fn decode_set<FIELDS, SET, D, F>(
868        &mut self,
869        _: Tag,
870        decode_fn: D,
871        field_fn: F,
872    ) -> Result<SET, Self::Error>
873    where
874        SET: Decode + crate::types::Constructed,
875        FIELDS: Decode,
876        D: Fn(&mut Self, usize, Tag) -> Result<FIELDS, Self::Error>,
877        F: FnOnce(Vec<FIELDS>) -> Result<SET, Self::Error>,
878    {
879        let is_extensible = SET::EXTENDED_FIELDS
880            .is_some()
881            .then(|| self.parse_one_bit())
882            .transpose()?
883            .unwrap_or_default();
884
885        let bitmap = self.parse_optional_and_default_field_bitmap(&SET::FIELDS)?;
886        let field_map = SET::FIELDS
887            .optional_and_default_fields()
888            .zip(bitmap.into_iter().map(|b| *b))
889            .collect::<alloc::collections::BTreeMap<_, _>>();
890
891        let fields = {
892            let mut fields = Vec::new();
893            let mut set_decoder = Self::new(self.input(), self.options);
894            set_decoder.extension_fields = SET::EXTENDED_FIELDS;
895            set_decoder.extensions_present = is_extensible.then_some(None);
896            set_decoder.fields = SET::FIELDS
897                .optional_and_default_fields()
898                .zip(bitmap.into_iter().map(|b| *b))
899                .collect();
900
901            let mut field_indices = SET::FIELDS.iter().enumerate().collect::<Vec<_>>();
902            field_indices.sort_by(|(_, a), (_, b)| {
903                a.tag_tree.smallest_tag().cmp(&b.tag_tree.smallest_tag())
904            });
905            for (indice, field) in field_indices.into_iter() {
906                match field_map.get(&field).copied() {
907                    Some(true) | None => {
908                        fields.push((decode_fn)(&mut set_decoder, indice, field.tag)?)
909                    }
910                    Some(false) => {}
911                }
912            }
913
914            for (indice, field) in SET::EXTENDED_FIELDS
915                .iter()
916                .flat_map(|fields| fields.iter())
917                .enumerate()
918            {
919                fields.push((decode_fn)(
920                    &mut set_decoder,
921                    indice + SET::FIELDS.len(),
922                    field.tag,
923                )?)
924            }
925
926            self.input = set_decoder.input;
927            fields
928        };
929
930        (field_fn)(fields)
931    }
932
933    fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error> {
934        self.decode_optional_with_tag(D::TAG)
935    }
936
937    /// Decode an the optional value in a `SEQUENCE` or `SET` with `tag`.
938    /// Passing the correct tag is required even when used with codecs where
939    /// the tag is not present.
940    fn decode_optional_with_tag<D: Decode>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error> {
941        let is_present = self.require_field(tag)?;
942
943        if is_present {
944            D::decode_with_tag(self, tag).map(Some)
945        } else {
946            Ok(None)
947        }
948    }
949
950    fn decode_optional_with_constraints<D: Decode>(
951        &mut self,
952        constraints: Constraints,
953    ) -> Result<Option<D>, Self::Error> {
954        let is_present = self.require_field(D::TAG)?;
955
956        if is_present {
957            D::decode_with_constraints(self, constraints).map(Some)
958        } else {
959            Ok(None)
960        }
961    }
962
963    fn decode_optional_with_tag_and_constraints<D: Decode>(
964        &mut self,
965        tag: Tag,
966        constraints: Constraints,
967    ) -> Result<Option<D>, Self::Error> {
968        let is_present = self.require_field(tag)?;
969
970        if is_present {
971            D::decode_with_tag_and_constraints(self, tag, constraints).map(Some)
972        } else {
973            Ok(None)
974        }
975    }
976
977    fn decode_choice<D>(&mut self, constraints: Constraints) -> Result<D, Self::Error>
978    where
979        D: crate::types::DecodeChoice,
980    {
981        let is_extensible = self.parse_extensible_bit(&constraints)?;
982        let variants = crate::types::variants::Variants::from_static(if is_extensible {
983            D::EXTENDED_VARIANTS.unwrap_or(&[])
984        } else {
985            D::VARIANTS
986        });
987
988        let index = if variants.len() != 1 || is_extensible {
989            usize::try_from(if is_extensible {
990                self.parse_normally_small_integer()?
991            } else {
992                let variance = variants.len();
993                debug_assert!(variance > 0);
994                // https://github.com/XAMPPRocky/rasn/issues/168
995                // Choice index starts from zero, so we need to reduce variance by one
996                let choice_range =
997                    constraints::Value::new(constraints::Bounded::new(0, (variance - 1) as i128))
998                        .into();
999                self.parse_integer(Constraints::new(&[choice_range]))?
1000            })
1001            .map_err(|error| {
1002                DecodeError::choice_index_exceeds_platform_width(
1003                    usize::BITS,
1004                    error.into_original().bits(),
1005                    self.codec(),
1006                )
1007            })?
1008        } else {
1009            0
1010        };
1011
1012        let tag = variants.get(index).ok_or_else(|| {
1013            DecodeError::choice_index_not_found(index, variants.clone(), self.codec())
1014        })?;
1015
1016        if is_extensible {
1017            let bytes = self.decode_octets()?;
1018            let mut decoder = Decoder::new(&bytes, self.options);
1019            D::from_tag(&mut decoder, *tag)
1020        } else {
1021            D::from_tag(self, *tag)
1022        }
1023    }
1024
1025    fn decode_extension_addition_group<D: Decode + crate::types::Constructed>(
1026        &mut self,
1027    ) -> Result<Option<D>, Self::Error> {
1028        if !self.parse_extension_header()? {
1029            return Ok(None);
1030        }
1031
1032        let extension_is_present = self
1033            .extension_is_present()?
1034            .map(|(_, b)| b)
1035            .unwrap_or_default();
1036
1037        if !extension_is_present {
1038            return Ok(None);
1039        }
1040
1041        let bytes = self.decode_octets()?;
1042        let mut decoder = Decoder::new(&bytes, self.options);
1043
1044        D::decode(&mut decoder).map(Some)
1045    }
1046
1047    fn decode_extension_addition_with_constraints<D>(
1048        &mut self,
1049        constraints: Constraints,
1050    ) -> core::result::Result<Option<D>, Self::Error>
1051    where
1052        D: Decode,
1053    {
1054        if !self.parse_extension_header()? {
1055            return Ok(None);
1056        }
1057
1058        let extension_is_present = self
1059            .extension_is_present()?
1060            .map(|(_, b)| b)
1061            .unwrap_or_default();
1062
1063        if !extension_is_present {
1064            return Ok(None);
1065        }
1066
1067        let bytes = self.decode_octets()?;
1068        let mut decoder = Decoder::new(&bytes, self.options);
1069
1070        D::decode_with_constraints(&mut decoder, constraints).map(Some)
1071    }
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076    use super::*;
1077
1078    #[test]
1079    fn bitvec() {
1080        use bitvec::prelude::*;
1081        assert_eq!(
1082            to_vec(bitvec::bits![u8, Msb0;       0, 0, 0, 1, 1, 1, 0, 1]),
1083            vec![29]
1084        );
1085        assert_eq!(
1086            to_vec(&bitvec::bits![u8, Msb0; 1, 1, 0, 0, 0, 1, 1, 1, 0, 1][2..]),
1087            vec![29]
1088        );
1089    }
1090}