rasn/oer/
de.rs

1// ITU-T X.696 (02/2021) version of OER decoding
2// In OER, without knowledge of the type of the value encoded, it is not possible to determine
3// the structure of the encoding. In particular, the end of the encoding cannot be determined from
4// the encoding itself without knowledge of the type being encoded ITU-T X.696 (6.2).
5use super::enc::EncodingRules;
6use crate::oer::ranges;
7use crate::prelude::{
8    Any, BitString, BmpString, Constraints, Constructed, DecodeChoice, Enumerated, GeneralString,
9    GeneralizedTime, Ia5String, NumericString, ObjectIdentifier, PrintableString, SetOf,
10    TeletexString, UtcTime, VisibleString,
11};
12use crate::types::fields::{Field, Fields};
13use crate::{Codec, Decode, Tag};
14use alloc::{
15    collections::VecDeque,
16    string::{String, ToString},
17    vec::Vec,
18};
19use bitvec::field::BitField;
20use nom::{AsBytes, Slice};
21use num_integer::div_ceil;
22use num_traits::ToPrimitive;
23
24// Max length for data type can be 2^1016, below presented as byte array of unsigned int
25#[allow(unused)]
26const MAX_LENGTH: [u8; 127] = [0xff; 127];
27#[allow(unused)]
28const MAX_LENGTH_LENGTH: usize = MAX_LENGTH.len();
29use crate::error::{CoerDecodeErrorKind, DecodeError, DecodeErrorKind, OerDecodeErrorKind};
30
31type InputSlice<'input> = nom_bitvec::BSlice<'input, u8, bitvec::order::Msb0>;
32
33#[derive(Clone, Copy, Debug)]
34pub struct DecoderOptions {
35    encoding_rules: EncodingRules, // default COER
36}
37impl DecoderOptions {
38    #[must_use]
39    pub const fn oer() -> Self {
40        Self {
41            encoding_rules: EncodingRules::Oer,
42        }
43    }
44    #[must_use]
45    pub const fn coer() -> Self {
46        Self {
47            encoding_rules: EncodingRules::Coer,
48        }
49    }
50    #[must_use]
51    fn current_codec(self) -> Codec {
52        match self.encoding_rules {
53            EncodingRules::Oer => Codec::Oer,
54            EncodingRules::Coer => Codec::Coer,
55        }
56    }
57}
58
59pub struct Decoder<'input> {
60    input: InputSlice<'input>,
61    options: DecoderOptions,
62    fields: VecDeque<(Field, bool)>,
63    extension_fields: Option<Fields>,
64    extensions_present: Option<Option<VecDeque<(Field, bool)>>>,
65}
66
67impl<'input> Decoder<'input> {
68    #[must_use]
69    pub fn new(input: &'input crate::types::BitStr, options: DecoderOptions) -> Self {
70        Self {
71            input: input.into(),
72            options,
73            fields: <_>::default(),
74            extension_fields: <_>::default(),
75            extensions_present: <_>::default(),
76        }
77    }
78    #[must_use]
79    fn codec(&self) -> Codec {
80        self.options.current_codec()
81    }
82    fn parse_one_bit(&mut self) -> Result<bool, DecodeError> {
83        let (input, boolean) = nom::bytes::streaming::take(1u8)(self.input)
84            .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
85        self.input = input;
86        Ok(boolean[0])
87    }
88    fn parse_one_byte(&mut self) -> Result<u8, DecodeError> {
89        let (input, byte) = nom::bytes::streaming::take(8u8)(self.input)
90            .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
91
92        self.input = input;
93        Ok(byte.as_bytes()[0])
94    }
95    fn drop_bits(&mut self, num: usize) -> Result<(), DecodeError> {
96        let (input, _) = nom::bytes::streaming::take(num)(self.input)
97            .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
98        self.input = input;
99        Ok(())
100    }
101    fn parse_tag(&mut self) -> Result<Tag, DecodeError> {
102        // Seems like tag number
103        use crate::types::Class;
104        let first_byte = self.parse_one_byte()?;
105        let class = match first_byte >> 6 {
106            0b00 => Class::Universal,
107            0b01 => Class::Application,
108            0b10 => Class::Context,
109            0b11 => Class::Private,
110            class => return Err(OerDecodeErrorKind::InvalidTagClassOnChoice { class }.into()),
111        };
112        let tag_number = first_byte & 0b0011_1111;
113        if tag_number == 0b11_1111 {
114            // Long form
115            let mut tag_number = 0u32;
116            let mut next_byte = self.parse_one_byte()?;
117            if next_byte & 0b1000_0000 > 0 {
118                return Err(OerDecodeErrorKind::invalid_tag_number_on_choice(u32::from(
119                    next_byte & 0b1000_0000,
120                )));
121            }
122            loop {
123                // Constructs tag number from multiple 7-bit sized chunks
124                tag_number = tag_number
125                    .checked_shl(7)
126                    .ok_or(OerDecodeErrorKind::invalid_tag_number_on_choice(tag_number))?
127                    | u32::from(next_byte & 0b0111_1111);
128                if next_byte & 0b1000_0000 == 0 {
129                    break;
130                }
131                next_byte = self.parse_one_byte()?;
132            }
133            Ok(Tag::new(class, tag_number))
134        } else {
135            Ok(Tag::new(class, u32::from(tag_number)))
136        }
137    }
138    fn parse_byte_and_leading_zeros(&mut self) -> Result<u8, DecodeError> {
139        // In OER decoding, there might be cases when there are multiple zero octets as padding
140        // or the length is encoded in more than one octet.
141        let mut leading_zeroes = 0usize;
142        let mut only_zeros = true;
143        let mut possible_value: u8 = 0;
144        // Parse leading zeros but also note if there are only zeros
145        while let Ok(data) = self.parse_one_byte() {
146            if data != 0 {
147                possible_value = data;
148                only_zeros = false;
149                break;
150            }
151            leading_zeroes += 1;
152        }
153        if self.options.encoding_rules.is_coer() && leading_zeroes > 1 {
154            return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
155                msg: "Leading zeros are not allowed in COER on length determinant or Enumerated index value.".to_string(),
156            }
157                .into());
158        }
159        if only_zeros {
160            // Only zeros, length is zero
161            return Ok(0);
162        }
163        Ok(possible_value)
164    }
165    /// There is a short form and long form for length determinant in OER encoding.
166    /// In short form one octet is used and the leftmost bit is always zero; length is less than 128
167    /// Max length for data type could be 2^1016 - 1 octets, however on this implementation it is limited to `usize::MAX`
168    fn decode_length(&mut self) -> Result<usize, DecodeError> {
169        let possible_length = self.parse_byte_and_leading_zeros()?;
170        if possible_length < 128 {
171            Ok(usize::from(possible_length))
172        } else {
173            // We have the length of the length, mask and extract only 7 bis
174            let length = possible_length & 0x7fu8;
175            // Length of length cannot be zero
176            if length == 0 {
177                return Err(DecodeError::from_kind(
178                    DecodeErrorKind::ZeroLengthOfLength,
179                    self.codec(),
180                ));
181            }
182            // Should not overflow, max size 8 x 127 = 1016 < u16::MAX
183            let result: Result<(InputSlice, InputSlice), DecodeError> =
184                nom::bytes::streaming::take((length as u16) * 8)(self.input)
185                    .map_err(|e| DecodeError::map_nom_err(e, self.codec()));
186
187            match result {
188                Ok((input, data)) => {
189                    self.input = input;
190                    if data.len() > usize::BITS as usize {
191                        return Err(DecodeError::length_exceeds_platform_width(
192                            "Length is larger than usize can present, and therefore unlikely that data can be processed.".to_string(),
193                            self.codec(),
194                        ));
195                    }
196                    if self.options.encoding_rules.is_coer() && input.leading_zeros() > 8 {
197                        return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
198                            msg: "Length value should not have leading zeroes in COER".to_string(),
199                        }
200                        .into());
201                    }
202                    let length = data.load_be::<usize>();
203                    if length < 128 && self.options.encoding_rules.is_coer() {
204                        return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
205                            msg: "Length determinant could have been encoded in short form."
206                                .to_string(),
207                        }
208                        .into());
209                    }
210                    Ok(length.to_usize().unwrap_or(0))
211                }
212                Err(e) => Err(e),
213            }
214        }
215    }
216    /// Extracts data from input by length and updates the input
217    /// Since we rely on memory and `BitSlice`, we cannot handle larger data length than `0x1fff_ffff_ffff_ffff`
218    /// 'length' is the length of the data in bytes (octets)
219    /// Returns the data
220    fn extract_data_by_length(&mut self, length: usize) -> Result<InputSlice, DecodeError> {
221        if length == 0 {
222            return Ok(InputSlice::from(bitvec::slice::BitSlice::from_slice(&[])));
223        }
224        if length > bitvec::slice::BitSlice::<usize>::MAX_BITS {
225            return Err(DecodeError::length_exceeds_platform_width(
226                "Length is larger than BitSlice can hold data on this platform.".to_string(),
227                self.codec(),
228            ));
229        }
230        let (input, data) = nom::bytes::streaming::take(length * 8)(self.input)
231            .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
232
233        self.input = input;
234        Ok(data)
235    }
236    fn decode_integer_from_bytes<I: crate::types::IntegerType>(
237        &mut self,
238        signed: bool,
239        length: Option<usize>,
240    ) -> Result<I, DecodeError> {
241        let final_length = match length {
242            Some(l) => l,
243            None => self.decode_length()?,
244        };
245
246        let codec = self.codec();
247        let coer = self.options.encoding_rules.is_coer();
248        let data = self.extract_data_by_length(final_length)?;
249        // // Constrained data can correctly include leading zeros, unconstrained not
250        if coer && !signed && data.leading_zeros() > 8 && length.is_none() {
251            return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
252                msg: "Leading zeros are not allowed on unsigned Integer value in COER.".to_string(),
253            }
254            .into());
255        }
256
257        if signed {
258            Ok(I::try_from_signed_bytes(data.as_bytes(), codec)?)
259        } else {
260            Ok(I::try_from_unsigned_bytes(data.as_bytes(), codec)?)
261        }
262    }
263    fn decode_integer_with_constraints<I: crate::types::IntegerType>(
264        &mut self,
265        constraints: &Constraints,
266    ) -> Result<I, DecodeError> {
267        // Only 'value' constraint is OER visible for integer
268        if let Some(value) = constraints.value() {
269            ranges::determine_integer_size_and_sign(&value, self.input, |_, sign, octets| {
270                let integer = self.decode_integer_from_bytes::<I>(sign, octets.map(usize::from))?;
271
272                // if the value is too large for a i128, the constraint isn't satisfied
273                let constraint_integer = integer.clone().try_into().map_err(|_| {
274                    DecodeError::value_constraint_not_satisfied(
275                        integer.clone().into(),
276                        value.constraint.0,
277                        self.codec(),
278                    )
279                })?;
280
281                if value.constraint.contains(&constraint_integer) {
282                    Ok(integer)
283                } else {
284                    Err(DecodeError::value_constraint_not_satisfied(
285                        integer.into(),
286                        value.constraint.0,
287                        self.codec(),
288                    ))
289                }
290            })
291        } else {
292            // No constraints
293            self.decode_integer_from_bytes::<I>(true, None)
294        }
295    }
296    fn parse_bit_string(&mut self, constraints: &Constraints) -> Result<BitString, DecodeError> {
297        if let Some(size) = constraints.size() {
298            // Fixed size, only data is included
299            if size.constraint.is_fixed() && size.extensible.is_none() {
300                let length = size.constraint.as_start().ok_or_else(|| {
301                    Err(DecodeError::size_constraint_not_satisfied(
302                        None,
303                        "Fixed size constraint should have value".to_string(),
304                        self.codec(),
305                    ))
306                });
307                return match length {
308                    Ok(length) => {
309                        let bytes_required = div_ceil(*length, 8);
310                        let data = self
311                            .extract_data_by_length(bytes_required)?
312                            .slice(..*length);
313                        Ok(BitString::from_bitslice(&data))
314                    }
315                    Err(e) => e,
316                };
317            }
318        }
319        let length = self.decode_length()?;
320        if length == 0 {
321            return Ok(BitString::new());
322        }
323
324        let num_unused_bits = self.parse_one_byte()?;
325        if length == 1 && num_unused_bits > 0 {
326            return Err(OerDecodeErrorKind::invalid_bit_string(
327                "Length includes only initial octet. There cannot be unused bits on the subsequent octects as there isn't any.".to_string(),
328            ));
329        }
330        if num_unused_bits > 7 {
331            return Err(OerDecodeErrorKind::invalid_bit_string(
332                "Marked number of unused bits should be less than 8 when decoding OER".to_string(),
333            ));
334        }
335        // Remove one from length as one describes trailing zeros...
336        let data_bit_length: usize = (&length - 1usize).checked_mul(8).ok_or_else(|| {
337            DecodeError::length_exceeds_platform_width(
338                "Total length exceeds BitSlice max usize when decoding BitString".to_string(),
339                self.codec(),
340            )
341        })?;
342        let data = self
343            .extract_data_by_length(length - 1)?
344            .slice(..(data_bit_length - num_unused_bits as usize));
345        Ok(BitString::from_bitslice(data.into()))
346    }
347    fn parse_known_multiplier_string<
348        T: crate::types::strings::StaticPermittedAlphabet + crate::types::AsnType,
349    >(
350        &mut self,
351        constraints: &Constraints,
352    ) -> Result<T, DecodeError> {
353        if let Some(size) = constraints.size() {
354            // Fixed size, only data is included
355            if size.constraint.is_fixed() && size.extensible.is_none() {
356                let data = self
357                    .extract_data_by_length(*size.constraint.as_start().unwrap())
358                    .map(|data| data.to_bitvec())?;
359                return T::try_from_bits(data, 8).map_err(|e| {
360                    DecodeError::string_conversion_failed(T::TAG, e.to_string(), self.codec())
361                });
362            }
363        }
364        let length = self.decode_length()?;
365        T::try_from_bits(self.extract_data_by_length(length)?.to_bitvec(), 8)
366            .map_err(|e| DecodeError::string_conversion_failed(T::TAG, e.to_string(), self.codec()))
367    }
368    fn parse_optional_and_default_field_bitmap(
369        &mut self,
370        fields: &Fields,
371    ) -> Result<InputSlice<'input>, DecodeError> {
372        let (input, bitset) =
373            nom::bytes::streaming::take(fields.number_of_optional_and_default_fields())(self.input)
374                .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
375
376        self.input = input;
377        Ok(bitset)
378    }
379    #[track_caller]
380    fn require_field(&mut self, tag: Tag) -> Result<bool, DecodeError> {
381        if self
382            .fields
383            .front()
384            .is_some_and(|field| field.0.tag_tree.smallest_tag() == tag)
385        {
386            Ok(self.fields.pop_front().unwrap().1)
387        } else {
388            Err(DecodeError::missing_tag_class_or_value_in_sequence_or_set(
389                tag.class,
390                tag.value,
391                self.codec(),
392            ))
393        }
394    }
395    fn extension_is_present(&mut self) -> Result<Option<(Field, bool)>, DecodeError> {
396        let codec = self.codec();
397        Ok(self
398            .extensions_present
399            .as_mut()
400            .ok_or_else(|| DecodeError::type_not_extensible(codec))?
401            .as_mut()
402            .ok_or_else(|| DecodeError::type_not_extensible(codec))?
403            .pop_front())
404    }
405    fn parse_extension_header(&mut self) -> Result<bool, DecodeError> {
406        match self.extensions_present {
407            Some(Some(_)) => return Ok(true),
408            Some(None) => (),
409            None => return Ok(false),
410        }
411        let extensions_length = self.decode_length()?;
412        // If length is 0, then there is only initial octet
413        if extensions_length < 1u8.into() {
414            return Err(OerDecodeErrorKind::invalid_extension_header(
415                "Extension length should be at least 1 byte".to_string(),
416            ));
417        }
418        // Must be at least 8 bits at this point or error is already raised
419        let bitfield = self.extract_data_by_length(extensions_length)?.to_bitvec();
420        // let mut missing_bits: bitvec::vec::BitVec<u8, bitvec::order::Msb0>;
421        // Initial octet
422        let (unused_bits, bitfield) = bitfield.split_at(8);
423        let unused_bits: usize = unused_bits.load();
424
425        if unused_bits > bitfield.len() || unused_bits > 7 {
426            return Err(OerDecodeErrorKind::invalid_extension_header(
427                "Invalid extension bitfield initial octet".to_string(),
428            ));
429        }
430        let (bitfield, _) = bitfield.split_at(bitfield.len() - unused_bits);
431
432        let extensions_present: VecDeque<_> = self
433            .extension_fields
434            .as_ref()
435            .unwrap()
436            .iter()
437            .zip(bitfield.iter().map(|b| *b))
438            .collect();
439
440        for (field, is_present) in &extensions_present {
441            if field.is_not_optional_or_default() && !*is_present {
442                return Err(DecodeError::required_extension_not_present(
443                    field.tag,
444                    self.codec(),
445                ));
446            }
447        }
448        self.extensions_present = Some(Some(extensions_present));
449
450        Ok(true)
451    }
452    /// Parse preamble, returns field bitmap and if extensible is present
453    fn parse_preamble<D>(&mut self) -> Result<(InputSlice, bool), DecodeError>
454    where
455        D: Constructed,
456    {
457        let is_extensible = D::EXTENDED_FIELDS.is_some();
458        let extensible_present = if is_extensible {
459            self.parse_one_bit()?
460        } else {
461            false
462        };
463        let bitmap = self.parse_optional_and_default_field_bitmap(&D::FIELDS)?;
464        let preamble_length = if is_extensible {
465            1usize + bitmap.len()
466        } else {
467            bitmap.len()
468        };
469        self.drop_bits((8 - preamble_length % 8) % 8)?;
470
471        debug_assert_eq!(self.input.len() % 8, 0);
472        Ok((bitmap, extensible_present))
473    }
474}
475
476impl<'input> crate::Decoder for Decoder<'input> {
477    type Error = DecodeError;
478
479    fn codec(&self) -> Codec {
480        self.codec()
481    }
482    fn decode_any(&mut self) -> Result<Any, Self::Error> {
483        panic!("Not every type can be decoded as Any in OER.")
484    }
485
486    fn decode_bit_string(
487        &mut self,
488        _: Tag,
489        constraints: Constraints,
490    ) -> Result<BitString, Self::Error> {
491        self.parse_bit_string(&constraints)
492    }
493    /// One octet is used to present bool, false is 0x0 and true is value up to 0xff
494    /// In COER, only 0x0 and 0xff are valid values
495    fn decode_bool(&mut self, _: Tag) -> Result<bool, Self::Error> {
496        let byte = self.parse_one_byte()?;
497        Ok(match byte {
498            0 => false,
499            0xFF => true,
500            _ if self.options.encoding_rules.is_oer() => true,
501            _ => {
502                return Err(DecodeError::from_kind(
503                    DecodeErrorKind::InvalidBool { value: byte },
504                    self.codec(),
505                ))
506            }
507        })
508    }
509
510    fn decode_enumerated<E: Enumerated>(&mut self, _: Tag) -> Result<E, Self::Error> {
511        let byte = self.parse_one_byte()?;
512        if byte < 128 {
513            // Short form, use value directly as unsigned integer
514            E::from_discriminant(isize::from(byte))
515                .ok_or_else(|| DecodeError::discriminant_value_not_found(byte.into(), self.codec()))
516        } else {
517            // Long form, value as signed integer. Previous byte is length of the subsequent octets
518            let length = byte & 0x7fu8;
519            let discriminant: isize = self
520                .decode_integer_from_bytes(true, Some(length.into()))
521                .map_err(|e| {
522                    if matches!(&*e.kind, DecodeErrorKind::IntegerOverflow { .. }) {
523                        DecodeError::length_exceeds_platform_width(
524                            "Enumerated discriminant value too large for this platform."
525                                .to_string(),
526                            self.codec(),
527                        )
528                    } else {
529                        e
530                    }
531                })?;
532
533            if (0..128).contains(&discriminant) && self.options.encoding_rules.is_coer() {
534                return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
535                    msg: "Enumerated discriminant should have been encoded in short form."
536                        .to_string(),
537                }
538                .into());
539            }
540            E::from_discriminant(discriminant).ok_or_else(|| {
541                DecodeError::discriminant_value_not_found(discriminant, self.codec())
542            })
543        }
544    }
545
546    fn decode_integer<I: crate::types::IntegerType>(
547        &mut self,
548        _: Tag,
549        constraints: Constraints,
550    ) -> Result<I, Self::Error> {
551        self.decode_integer_with_constraints::<I>(&constraints)
552    }
553
554    /// Null contains no data, so we just skip
555    fn decode_null(&mut self, _: Tag) -> Result<(), Self::Error> {
556        Ok(())
557    }
558
559    fn decode_object_identifier(&mut self, _: Tag) -> Result<ObjectIdentifier, Self::Error> {
560        let length = self.decode_length()?;
561        let ber_decoder = crate::ber::de::Decoder::new(&[], crate::ber::de::DecoderOptions::ber());
562        ber_decoder
563            .decode_object_identifier_from_bytes(self.extract_data_by_length(length)?.as_bytes())
564    }
565
566    fn decode_sequence<D, DF: FnOnce() -> D, F>(
567        &mut self,
568        _: Tag,
569        default_initializer_fn: Option<DF>,
570        decode_fn: F,
571    ) -> Result<D, Self::Error>
572    where
573        D: Constructed,
574
575        F: FnOnce(&mut Self) -> Result<D, Self::Error>,
576    {
577        // If there are no fields then the sequence is empty
578        // Or if all fields are optional and default and there is no data
579        if D::FIELDS.is_empty()
580            || D::FIELDS.len() == D::FIELDS.number_of_optional_and_default_fields()
581                && self.input.is_empty()
582        {
583            if let Some(default_initializer_fn) = default_initializer_fn {
584                return Ok((default_initializer_fn)());
585            }
586            return Err(DecodeError::from_kind(
587                DecodeErrorKind::UnexpectedEmptyInput,
588                self.codec(),
589            ));
590        }
591        // ### PREAMBLE ###
592        let (bitmap, extensible_present) = self.parse_preamble::<D>()?;
593        // ### ENDS
594        let fields = D::FIELDS
595            .optional_and_default_fields()
596            .zip(bitmap.into_iter().map(|b| *b))
597            .collect();
598
599        let value = {
600            let mut sequence_decoder = Self::new(self.input.0, self.options);
601            sequence_decoder.extension_fields = D::EXTENDED_FIELDS;
602            sequence_decoder.extensions_present = extensible_present.then_some(None);
603            sequence_decoder.fields = fields;
604            let value = decode_fn(&mut sequence_decoder)?;
605
606            self.input = sequence_decoder.input;
607            value
608        };
609
610        Ok(value)
611    }
612
613    fn decode_sequence_of<D: Decode>(
614        &mut self,
615        _: Tag,
616        _: Constraints,
617    ) -> Result<Vec<D>, Self::Error> {
618        let mut sequence_of = Vec::new();
619        let length_of_quantity = self.decode_length()?;
620        let coer = self.options.encoding_rules.is_coer();
621        let length_bits = self.extract_data_by_length(length_of_quantity)?;
622        if coer && length_bits.leading_zeros() > 8 {
623            return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
624                msg: "Quantity value in 'sequence/set of' should not have leading zeroes in COER"
625                    .to_string(),
626            }
627            .into());
628        }
629
630        let length = length_bits.load_be::<usize>();
631        let mut start = 1;
632        let mut decoder = Self::new(self.input.0, self.options);
633        while start <= length {
634            let value = D::decode(&mut decoder)?;
635            self.input = decoder.input;
636            sequence_of.push(value);
637            start += 1;
638        }
639        Ok(sequence_of)
640    }
641
642    fn decode_set_of<D: Decode + Ord>(
643        &mut self,
644        tag: Tag,
645        constraints: Constraints,
646    ) -> Result<SetOf<D>, Self::Error> {
647        self.decode_sequence_of(tag, constraints)
648            .map(|seq| seq.into_iter().collect())
649    }
650
651    fn decode_octet_string(
652        &mut self,
653        _: Tag,
654        constraints: Constraints,
655    ) -> Result<Vec<u8>, Self::Error> {
656        if let Some(size) = constraints.size() {
657            // Fixed size, only data is included
658            if size.constraint.is_fixed() && size.extensible.is_none() {
659                let data = self
660                    .extract_data_by_length(*size.constraint.as_start().ok_or_else(|| {
661                        DecodeError::size_constraint_not_satisfied(
662                            None,
663                            "Fixed size constraint should have value when decoding Octet String"
664                                .to_string(),
665                            self.codec(),
666                        )
667                    })?)
668                    .map(|data| data.as_bytes().to_vec());
669                return data;
670            }
671        }
672        let length = self.decode_length()?;
673        self.extract_data_by_length(length)
674            .map(|data| data.as_bytes().to_vec())
675    }
676
677    fn decode_utf8_string(
678        &mut self,
679        tag: Tag,
680        constraints: Constraints,
681    ) -> Result<String, Self::Error> {
682        self.decode_octet_string(tag, constraints)
683            .and_then(|bytes| {
684                String::from_utf8(bytes).map_err(|e| {
685                    DecodeError::string_conversion_failed(
686                        Tag::UTF8_STRING,
687                        e.to_string(),
688                        self.codec(),
689                    )
690                })
691            })
692    }
693
694    fn decode_visible_string(
695        &mut self,
696        _: Tag,
697        constraints: Constraints,
698    ) -> Result<VisibleString, Self::Error> {
699        self.parse_known_multiplier_string(&constraints)
700    }
701
702    fn decode_general_string(
703        &mut self,
704        tag: Tag,
705        constraints: Constraints,
706    ) -> Result<GeneralString, Self::Error> {
707        GeneralString::try_from(self.decode_octet_string(tag, constraints)?).map_err(|e| {
708            DecodeError::string_conversion_failed(Tag::GENERAL_STRING, e.to_string(), self.codec())
709        })
710    }
711
712    fn decode_ia5_string(
713        &mut self,
714        _: Tag,
715        constraints: Constraints,
716    ) -> Result<Ia5String, Self::Error> {
717        self.parse_known_multiplier_string(&constraints)
718    }
719
720    fn decode_printable_string(
721        &mut self,
722        _: Tag,
723        constraints: Constraints,
724    ) -> Result<PrintableString, Self::Error> {
725        self.parse_known_multiplier_string(&constraints)
726    }
727
728    fn decode_numeric_string(
729        &mut self,
730        _: Tag,
731        constraints: Constraints,
732    ) -> Result<NumericString, Self::Error> {
733        self.parse_known_multiplier_string(&constraints)
734    }
735
736    fn decode_teletex_string(
737        &mut self,
738        tag: Tag,
739        constraints: Constraints,
740    ) -> Result<TeletexString, Self::Error> {
741        // Teletex conversion cannot fail
742        Ok(TeletexString::from(
743            self.decode_octet_string(tag, constraints)?,
744        ))
745    }
746
747    fn decode_bmp_string(
748        &mut self,
749        _: Tag,
750        constraints: Constraints,
751    ) -> Result<BmpString, Self::Error> {
752        self.parse_known_multiplier_string(&constraints)
753    }
754
755    fn decode_explicit_prefix<D: Decode>(&mut self, _tag: Tag) -> Result<D, Self::Error> {
756        D::decode(self)
757    }
758
759    fn decode_utc_time(&mut self, tag: Tag) -> Result<UtcTime, Self::Error> {
760        let string = String::from_utf8(self.decode_octet_string(tag, Constraints::default())?)
761            .map_err(|_| {
762                DecodeError::string_conversion_failed(
763                    Tag::UTF8_STRING,
764                    "UTCTime should be UTF8 encoded.".to_string(),
765                    self.codec(),
766                )
767            })?;
768        crate::der::de::Decoder::parse_canonical_utc_time_string(&string)
769    }
770
771    fn decode_generalized_time(&mut self, tag: Tag) -> Result<GeneralizedTime, Self::Error> {
772        let string = String::from_utf8(self.decode_octet_string(tag, Constraints::default())?)
773            .map_err(|_| {
774                DecodeError::string_conversion_failed(
775                    Tag::UTF8_STRING,
776                    "GeneralizedTime should be UTF8 encoded".to_string(),
777                    self.codec(),
778                )
779            })?;
780        crate::der::de::Decoder::parse_canonical_generalized_time_string(string)
781    }
782
783    fn decode_set<FIELDS, SET, D, F>(
784        &mut self,
785        _: Tag,
786        decode_fn: D,
787        field_fn: F,
788    ) -> Result<SET, Self::Error>
789    where
790        SET: Decode + Constructed,
791        FIELDS: Decode,
792        D: Fn(&mut Self, usize, Tag) -> Result<FIELDS, Self::Error>,
793        F: FnOnce(Vec<FIELDS>) -> Result<SET, Self::Error>,
794    {
795        let (bitmap, extensible_present) = self.parse_preamble::<SET>()?;
796
797        let field_map = SET::FIELDS
798            .optional_and_default_fields()
799            .zip(bitmap.into_iter().map(|b| *b))
800            .collect::<alloc::collections::BTreeMap<_, _>>();
801
802        let decoder_fields = SET::FIELDS
803            .optional_and_default_fields()
804            .zip(bitmap.into_iter().map(|b| *b))
805            .collect();
806
807        let fields = {
808            let mut fields = Vec::new();
809            let mut set_decoder = Self::new(self.input.0, self.options);
810            set_decoder.extension_fields = SET::EXTENDED_FIELDS;
811            set_decoder.extensions_present = extensible_present.then_some(None);
812            set_decoder.fields = decoder_fields;
813
814            let mut field_indices = SET::FIELDS.iter().enumerate().collect::<Vec<_>>();
815            field_indices.sort_by(|(_, a), (_, b)| {
816                a.tag_tree.smallest_tag().cmp(&b.tag_tree.smallest_tag())
817            });
818            for (indice, field) in field_indices {
819                match field_map.get(&field).copied() {
820                    Some(true) | None => {
821                        fields.push(decode_fn(&mut set_decoder, indice, field.tag)?);
822                    }
823                    Some(false) => {}
824                }
825            }
826            for (indice, field) in SET::EXTENDED_FIELDS
827                .iter()
828                .flat_map(Fields::iter)
829                .enumerate()
830            {
831                fields.push(decode_fn(
832                    &mut set_decoder,
833                    indice + SET::FIELDS.len(),
834                    field.tag,
835                )?);
836            }
837
838            self.input = set_decoder.input;
839            fields
840        };
841
842        field_fn(fields)
843    }
844
845    fn decode_choice<D>(&mut self, constraints: Constraints) -> Result<D, Self::Error>
846    where
847        D: DecodeChoice,
848    {
849        let is_extensible = constraints.extensible();
850        let tag: Tag = self.parse_tag()?;
851        let is_root_extension = crate::TagTree::tag_contains(&tag, D::VARIANTS);
852        let is_extended_extension =
853            crate::TagTree::tag_contains(&tag, D::EXTENDED_VARIANTS.unwrap_or(&[]));
854        if is_root_extension {
855            D::from_tag(self, tag)
856        } else if is_extensible && is_extended_extension {
857            let options = self.options;
858            let length = self.decode_length()?;
859            let bytes = self.extract_data_by_length(length)?;
860            let mut decoder = Decoder::new(&bytes, options);
861            D::from_tag(&mut decoder, tag)
862        } else {
863            return Err(OerDecodeErrorKind::invalid_tag_variant_on_choice(
864                tag,
865                is_extensible,
866            ));
867        }
868    }
869
870    fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error> {
871        self.decode_optional_with_tag(D::TAG)
872    }
873
874    fn decode_optional_with_tag<D: Decode>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error> {
875        let is_present = self.require_field(tag)?;
876        if is_present {
877            D::decode_with_tag(self, tag).map(Some)
878        } else {
879            Ok(None)
880        }
881    }
882
883    fn decode_optional_with_constraints<D: Decode>(
884        &mut self,
885        constraints: Constraints,
886    ) -> Result<Option<D>, Self::Error> {
887        let is_present = self.require_field(D::TAG)?;
888        if is_present {
889            D::decode_with_constraints(self, constraints).map(Some)
890        } else {
891            Ok(None)
892        }
893    }
894
895    fn decode_optional_with_tag_and_constraints<D: Decode>(
896        &mut self,
897        tag: Tag,
898        constraints: Constraints,
899    ) -> Result<Option<D>, Self::Error> {
900        let is_present = self.require_field(tag)?;
901        if is_present {
902            D::decode_with_tag_and_constraints(self, tag, constraints).map(Some)
903        } else {
904            Ok(None)
905        }
906    }
907
908    fn decode_extension_addition_with_constraints<D>(
909        &mut self,
910        constraints: Constraints,
911    ) -> Result<Option<D>, Self::Error>
912    where
913        D: Decode,
914    {
915        if !self.parse_extension_header()? {
916            return Ok(None);
917        }
918
919        let extension_is_present = self.extension_is_present()?.is_some_and(|(_, b)| b);
920
921        if !extension_is_present {
922            return Ok(None);
923        }
924
925        // Values of the extensions are only left, encoded as Open type
926        // TODO vec without conversion to bitslice
927        let bytes = self.decode_octet_string(Tag::OCTET_STRING, Constraints::default())?;
928        let mut decoder = Decoder::new(bitvec::slice::BitSlice::from_slice(&bytes), self.options);
929        D::decode_with_constraints(&mut decoder, constraints).map(Some)
930    }
931
932    fn decode_extension_addition_group<D: Decode + Constructed>(
933        &mut self,
934    ) -> Result<Option<D>, Self::Error> {
935        if !self.parse_extension_header()? {
936            return Ok(None);
937        }
938
939        let extension_is_present = self.extension_is_present()?.is_some_and(|(_, b)| b);
940
941        if !extension_is_present {
942            return Ok(None);
943        }
944
945        // Values of the extensions are only left, inner type encoded as Open type
946        // TODO vec without conversion to bitslice
947        let bytes = self.decode_octet_string(Tag::OCTET_STRING, Constraints::default())?;
948        let mut decoder = Decoder::new(bitvec::slice::BitSlice::from_slice(&bytes), self.options);
949        D::decode(&mut decoder).map(Some)
950    }
951}
952
953#[cfg(test)]
954#[allow(clippy::assertions_on_constants)]
955mod tests {
956    use num_bigint::BigUint;
957
958    use super::*;
959    use crate::types::constraints::{Bounded, Constraint, Constraints, Extensible, Size, Value};
960    use bitvec::prelude::BitSlice;
961    use num_bigint::BigInt;
962
963    #[test]
964    fn test_decode_bool() {
965        let decoded: bool = crate::oer::decode(&[0xffu8]).unwrap();
966        assert!(decoded);
967        let decoded: bool = crate::oer::decode(&[0u8]).unwrap();
968        assert!(!decoded);
969        let decoded: bool = crate::oer::decode(&[0xffu8, 0xff]).unwrap();
970        assert!(decoded);
971        let decoded: bool = crate::oer::decode(&[0x33u8, 0x0]).unwrap();
972        assert!(decoded);
973    }
974
975    #[test]
976    fn test_decode_length_invalid() {
977        let data: BitString = BitString::from_slice(&[0xffu8]);
978        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
979        // Length determinant is > 127 without subsequent bytes
980        assert!(decoder.decode_length().is_err());
981        // Still missing some data
982        let data: BitString = BitString::from_slice(&[0xffu8, 0xff]);
983        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
984        // Length determinant is > 127 without subsequent bytes
985        assert!(decoder.decode_length().is_err());
986    }
987
988    #[test]
989    fn test_decode_length_valid() {
990        // Max length
991        let max_length: BigUint = BigUint::from(2u8).pow(1016u32) - BigUint::from(1u8);
992        assert_eq!(max_length.to_bytes_be(), MAX_LENGTH);
993        assert_eq!(max_length.to_bytes_be().len(), MAX_LENGTH_LENGTH);
994        // Unfortunately we cannot support lengths > 2^64 - 1 at the moment
995        // Nor larger than BitSlice::<usize>::MAX_BITS
996        assert!(max_length > usize::MAX.into());
997        assert!(usize::MAX > BitSlice::<usize>::MAX_BITS);
998
999        // # SHORT FORM
1000        let data: BitString = BitString::from_slice(&[0x01u8, 0xff]);
1001        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1002        assert_eq!(decoder.decode_length().unwrap(), 1);
1003        let data: BitString = BitString::from_slice(&[0x03u8, 0xff, 0xff, 0xfe]);
1004        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1005        assert_eq!(decoder.decode_length().unwrap(), 3);
1006        // Max for short form
1007        let mut data: [u8; 0x80] = [0xffu8; 0x80];
1008        data[0] = 0x7f; // length determinant
1009        let data: BitString = BitString::from_slice(&data);
1010        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1011        assert_eq!(decoder.decode_length().unwrap(), 127);
1012
1013        // # LONG FORM
1014        // Length of the length should be 2 octets, 0x7f - 0x82 = 2, length is 258 octets
1015        let length: [u8; 1] = [0x82u8]; // first bit is 1, remaining tells length of the length
1016        let length_determinant: [u8; 0x02] = [0x01u8, 0x02];
1017        let data: [u8; 258] = [0xffu8; 258];
1018        let mut combined: [u8; 261] = [0x0; 261];
1019        combined[..1].copy_from_slice(&length);
1020        combined[1..=2].copy_from_slice(&length_determinant);
1021        combined[3..].copy_from_slice(&data);
1022
1023        let data: BitString = BitString::from_slice(&combined);
1024        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1025        assert_eq!(decoder.decode_length().unwrap(), 258usize);
1026    }
1027    #[test]
1028    fn test_long_form_length_decode() {
1029        let vc = BitString::from_slice(&[
1030            0x81, 0x80, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1031            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1032            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1033            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1034            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1035            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1036            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1037            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1038            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1039            0xff, 0xff, 0xff, 0xff,
1040        ]);
1041        let mut decoder = Decoder::new(&vc, DecoderOptions::oer());
1042        let number = BigInt::from(256).pow(127) - 1;
1043        let constraints = Constraints::default();
1044        let new_number: BigInt = decoder
1045            .decode_integer_with_constraints(&constraints)
1046            .unwrap();
1047        assert_eq!(new_number, number);
1048
1049        // Test maximum possible length
1050        let length: [u8; 1] = [0x80u8 + u8::try_from(usize::BITS / 8u32).unwrap()]; // first bit is 1, remaining tells length of the length
1051        let length_determinant: [u8; (usize::BITS / 8u32) as usize] =
1052            [0xff; (usize::BITS / 8u32) as usize];
1053        let mut combined: [u8; 1 + (usize::BITS / 8u32) as usize] =
1054            [0x0; 1 + (usize::BITS / 8u32) as usize];
1055        combined[..1].copy_from_slice(&length);
1056        combined[1..=(usize::BITS / 8u32) as usize].copy_from_slice(&length_determinant);
1057        let data: BitString = BitString::from_slice(&combined);
1058        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1059        let new_length = decoder.decode_length().unwrap();
1060        assert_eq!(new_length, usize::MAX);
1061        // Test length > usize::MAX
1062        let length: [u8; 1] = [0x80u8 + u8::try_from(usize::BITS / 8u32).unwrap() + 1]; // first bit is 1, remaining tells length of the length
1063        let length_determinant: [u8; (usize::BITS / 8u32) as usize + 1] =
1064            [0xff; (usize::BITS / 8u32) as usize + 1];
1065        let mut combined: [u8; 1 + (usize::BITS / 8u32) as usize + 1] =
1066            [0x0; 1 + (usize::BITS / 8u32) as usize + 1];
1067        combined[..1].copy_from_slice(&length);
1068        combined[1..=(usize::BITS / 8u32 + 1) as usize].copy_from_slice(&length_determinant);
1069        let data: BitString = BitString::from_slice(&combined);
1070        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1071        let new_length = decoder.decode_length();
1072        assert!(new_length.is_err());
1073    }
1074    #[test]
1075    fn test_integer_decode_with_constraints() {
1076        let range_bound = Bounded::<i128>::Range {
1077            start: 0.into(),
1078            end: 255.into(),
1079        };
1080        let value_range = &[Constraint::Value(Extensible::new(Value::new(range_bound)))];
1081        let consts = Constraints::new(value_range);
1082        let data = BitString::from_slice(&[0x01u8]);
1083        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1084        let decoded_int: i32 = decoder.decode_integer_with_constraints(&consts).unwrap();
1085        assert_eq!(decoded_int, 1);
1086
1087        let data = BitString::from_slice(&[0xffu8]);
1088        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1089        let decoded_int: i64 = decoder.decode_integer_with_constraints(&consts).unwrap();
1090        assert_eq!(decoded_int, 255);
1091
1092        let data = BitString::from_slice(&[0xffu8, 0xff]);
1093        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1094        let decoded_int: BigInt = decoder.decode_integer_with_constraints(&consts).unwrap();
1095        assert_eq!(decoded_int, 255.into());
1096
1097        let data = BitString::from_slice(&[0x02u8, 0xff, 0x01]);
1098        let mut decoder = Decoder::new(&data, DecoderOptions::oer());
1099        let decoded_int: BigInt = decoder
1100            .decode_integer_with_constraints(&Constraints::new(&[Constraint::Size(
1101                Size::new(Bounded::None).into(),
1102            )]))
1103            .unwrap();
1104        assert_eq!(decoded_int, BigInt::from(-255));
1105    }
1106}