rasn/
de.rs

1//! Generic ASN.1 decoding framework.
2
3use alloc::{boxed::Box, vec::Vec};
4use num_bigint::BigInt;
5
6use crate::error::DecodeError;
7use crate::types::{self, AsnType, Constraints, Enumerated, SetOf, Tag};
8
9pub use nom::Needed;
10pub use rasn_derive::Decode;
11
12/// A generic ASN.1 decoding iterator. JER and XER are not supported.
13pub fn iter<D: Decode>(input: &[u8], codec: crate::codec::Codec) -> Iter<'_, D> {
14    Iter::new(input, codec)
15}
16
17/// Represents the input buffer in one of two states:
18/// - `Borrowed(&[u8])` for the original input slice.
19/// - `Owned { data: Vec<u8>, pos: usize }` after extra data has been appended.
20///   Here `pos` tracks how many bytes have been consumed.
21enum IterBuffer<'a> {
22    Borrowed(&'a [u8]),
23    Owned { data: Vec<u8>, pos: usize },
24}
25
26impl IterBuffer<'_> {
27    /// Returns the current unread portion of the data.
28    fn as_slice(&self) -> &[u8] {
29        match self {
30            IterBuffer::Borrowed(slice) => slice,
31            IterBuffer::Owned { data, pos } => &data[*pos..],
32        }
33    }
34    /// Updates the buffer to account for the fact that `consumed` bytes were processed.
35    fn update_after_consumption(&mut self, consumed: usize) {
36        match self {
37            IterBuffer::Borrowed(slice) => *slice = &slice[consumed..],
38            IterBuffer::Owned { data, pos } => {
39                *pos += consumed;
40                // Drop the consumed bytes from the buffer once half of the data is already consumed.
41                if *pos > data.len() / 2 {
42                    data.drain(0..*pos);
43                    *pos = 0;
44                }
45            }
46        }
47    }
48
49    /// Converts a Borrowed variant to an Owned one.
50    #[allow(clippy::wrong_self_convention)]
51    fn to_owned(&mut self) {
52        if let IterBuffer::Borrowed(slice) = self {
53            let vec = slice.to_vec();
54            *self = IterBuffer::Owned { data: vec, pos: 0 };
55        }
56    }
57
58    /// Appends new bytes.
59    ///
60    /// Internal buffer is in the Owned state from this point forward.
61    fn extend(&mut self, bytes: &[u8]) {
62        self.to_owned();
63        if let IterBuffer::Owned { data, .. } = self {
64            data.extend_from_slice(bytes);
65        }
66    }
67}
68
69/// A generic ASN.1 decoding iterator.
70pub struct Iter<'input, D: Decode> {
71    buf: IterBuffer<'input>,
72    codec: crate::codec::Codec,
73    _kind: core::marker::PhantomData<D>,
74}
75
76impl<'input, D: Decode> Iter<'input, D> {
77    /// Create a new iterator from a borrowed input slice.
78    pub fn new(input: &'input [u8], codec: crate::codec::Codec) -> Self {
79        Self {
80            buf: IterBuffer::Borrowed(input),
81            codec,
82            _kind: core::marker::PhantomData,
83        }
84    }
85
86    /// Append new bytes to the input stream.
87    /// After this call the iterator will switch to using an owned buffer.
88    pub fn append_bytes(&mut self, bytes: &'input [u8]) {
89        self.buf.extend(bytes);
90    }
91}
92
93impl<D: Decode> Iterator for Iter<'_, D> {
94    type Item = Result<D, DecodeError>;
95
96    fn next(&mut self) -> Option<Self::Item> {
97        let input = self.buf.as_slice();
98        match self.codec.decode_from_binary_with_remainder(input) {
99            Ok((value, remainder)) => {
100                // Determine how many bytes were consumed.
101                let consumed = input.len() - remainder.len();
102                self.buf.update_after_consumption(consumed);
103                Some(Ok(value))
104            }
105            Err(err) => Some(Err(err)),
106        }
107    }
108}
109
110/// A **data type** that can decoded from any ASN.1 format.
111pub trait Decode: Sized + AsnType {
112    /// Decode this value from a given ASN.1 decoder.
113    ///
114    /// **Note for implementors** You typically do not need to implement this.
115    /// The default implementation will call [`Decode::decode_with_tag_and_constraints`] with
116    /// your types associated [`AsnType::TAG`]. You should only ever need to
117    /// implement this if you have a type that *cannot* be implicitly tagged,
118    /// such as a `CHOICE` type, which case you want to implement the decoding
119    /// in `decode`.
120    fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, D::Error> {
121        Self::decode_with_tag(decoder, Self::TAG)
122    }
123
124    /// Decode this value implicitly tagged with `tag` from a given ASN.1 decoder.
125    ///
126    /// **Note** For `CHOICE` and other types that cannot be implicitly tagged
127    /// this will **explicitly tag** the value, for all other types, it will
128    /// **implicitly** tag the value.
129    fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
130        Self::decode_with_tag_and_constraints(decoder, tag, Self::CONSTRAINTS)
131    }
132
133    /// Decode this value from a given ASN.1 decoder with a set of constraints
134    /// on what values of that type are allowed.
135    ///
136    /// **Note for implementors** You typically do not need to implement this.
137    /// The default implementation will call [`Decode::decode_with_tag_and_constraints`] with
138    /// your types associated [`AsnType::TAG`] and [`AsnType::CONSTRAINTS`].
139    fn decode_with_constraints<D: Decoder>(
140        decoder: &mut D,
141        constraints: Constraints,
142    ) -> Result<Self, D::Error> {
143        Self::decode_with_tag_and_constraints(decoder, Self::TAG, constraints)
144    }
145
146    /// Decode this value implicitly tagged with `tag` from a given ASN.1
147    /// decoder with a set of constraints on what values of that type are allowed.
148    ///
149    /// **Note** For `CHOICE` and other types that cannot be implicitly tagged
150    /// this will **explicitly tag** the value, for all other types, it will
151    /// **implicitly** tag the value.
152    fn decode_with_tag_and_constraints<D: Decoder>(
153        decoder: &mut D,
154        tag: Tag,
155        constraints: Constraints,
156    ) -> Result<Self, D::Error>;
157}
158
159/// A **data format** decode any ASN.1 data type.
160///
161/// Const `RCL` is the count of root components in the root component list of a sequence or set.
162/// Const `ECL` is the count of extension additions in the extension addition component type list in a sequence or set.
163pub trait Decoder<const RCL: usize = 0, const ECL: usize = 0>: Sized {
164    /// The associated success type returned on success.
165    type Ok;
166    /// The associated error type returned on failure.
167    type Error: Error + Into<crate::error::DecodeError> + From<crate::error::DecodeError>;
168    /// Helper type for decoding nested instances of `Decoder` with different fields.
169    type AnyDecoder<const R: usize, const E: usize>: Decoder<RCL, ECL, Ok = Self::Ok, Error = Self::Error>
170        + Decoder;
171
172    /// Returns codec variant of `Codec` that current decoder is decoding.
173    #[must_use]
174    fn codec(&self) -> crate::Codec;
175
176    /// Decode an unknown ASN.1 value identified by `tag` from the available input.
177    fn decode_any(&mut self) -> Result<types::Any, Self::Error>;
178    /// Decode a `BIT STRING` identified by `tag` from the available input.
179    fn decode_bit_string(
180        &mut self,
181        tag: Tag,
182        constraints: Constraints,
183    ) -> Result<types::BitString, Self::Error>;
184    /// Decode a `BOOL` identified by `tag` from the available input.
185    fn decode_bool(&mut self, tag: Tag) -> Result<bool, Self::Error>;
186    /// Decode an enumerated enum's discriminant identified by `tag` from the available input.
187    fn decode_enumerated<E: Enumerated>(&mut self, tag: Tag) -> Result<E, Self::Error>;
188    /// Decode a `INTEGER` identified by `tag` from the available input.
189    fn decode_integer<I: types::IntegerType>(
190        &mut self,
191        tag: Tag,
192        constraints: Constraints,
193    ) -> Result<I, Self::Error>;
194
195    /// Decode a `REAL` identified by `tag` from the available input.
196    fn decode_real<R: types::RealType>(
197        &mut self,
198        tag: Tag,
199        constraints: Constraints,
200    ) -> Result<R, Self::Error>;
201
202    /// Decode `NULL` identified by `tag` from the available input.
203    fn decode_null(&mut self, tag: Tag) -> Result<(), Self::Error>;
204    /// Decode a `OBJECT IDENTIFIER` identified by `tag` from the available input.
205    fn decode_object_identifier(
206        &mut self,
207        tag: Tag,
208    ) -> Result<types::ObjectIdentifier, Self::Error>;
209    /// Decode a `SEQUENCE` identified by `tag` from the available input. Returning
210    /// a new `Decoder` containing the sequence's contents to be decoded.
211    ///
212    /// Const `RC` is the count of root components in a sequence.
213    /// Const `EC` is the count of extension addition components in a sequence.
214    /// Generic `D` is the sequence type.
215    /// Generic `DF` is the closure that will initialize the sequence with default values, typically when no values are present.
216    /// Generic `F` is the closure that will decode the sequence by decoding the fields in the order as defined in the type.
217    /// NOTE: If you implement this manually, make sure to decode fields in the same order and pass the correct count of fields.
218    fn decode_sequence<const RC: usize, const EC: usize, D, DF, F>(
219        &mut self,
220        tag: Tag,
221        default_initializer_fn: Option<DF>,
222        decode_fn: F,
223    ) -> Result<D, Self::Error>
224    where
225        D: crate::types::Constructed<RC, EC>,
226        DF: FnOnce() -> D,
227        F: FnOnce(&mut Self::AnyDecoder<RC, EC>) -> Result<D, Self::Error>;
228    /// Decode a `SEQUENCE OF D` where `D: Decode` identified by `tag` from the available input.
229    fn decode_sequence_of<D: Decode>(
230        &mut self,
231        tag: Tag,
232        constraints: Constraints,
233    ) -> Result<Vec<D>, Self::Error>;
234    /// Decode a `SET OF D` where `D: Decode` identified by `tag` from the available input.
235    fn decode_set_of<D: Decode + Eq + core::hash::Hash>(
236        &mut self,
237        tag: Tag,
238        constraints: Constraints,
239    ) -> Result<types::SetOf<D>, Self::Error>;
240    /// Decode a `OCTET STRING` identified by `tag` from the available input.
241    fn decode_octet_string<'buf, T>(
242        &'buf mut self,
243        tag: Tag,
244        constraints: Constraints,
245    ) -> Result<T, Self::Error>
246    where
247        T: From<&'buf [u8]> + From<Vec<u8>>;
248
249    /// Decode a `UTF8 STRING` identified by `tag` from the available input.
250    fn decode_utf8_string(
251        &mut self,
252        tag: Tag,
253        constraints: Constraints,
254    ) -> Result<types::Utf8String, Self::Error>;
255
256    /// Decode a `VisibleString` identified by `tag` from the available input.
257    fn decode_visible_string(
258        &mut self,
259        tag: Tag,
260        constraints: Constraints,
261    ) -> Result<types::VisibleString, Self::Error>;
262
263    /// Decode a `GeneralString` identified by `tag` from the available input.
264    fn decode_general_string(
265        &mut self,
266        tag: Tag,
267        constraints: Constraints,
268    ) -> Result<types::GeneralString, Self::Error>;
269
270    /// Decode a `GraphicString` identified by `tag` from the available input.
271    fn decode_graphic_string(
272        &mut self,
273        tag: Tag,
274        constraints: Constraints,
275    ) -> Result<types::GraphicString, Self::Error>;
276
277    /// Decode a `Ia5String` identified by `tag` from the available input.
278    fn decode_ia5_string(
279        &mut self,
280        tag: Tag,
281        constraints: Constraints,
282    ) -> Result<types::Ia5String, Self::Error>;
283
284    /// Decode a `PrintableString` identified by `tag` from the available input.
285    fn decode_printable_string(
286        &mut self,
287        tag: Tag,
288        constraints: Constraints,
289    ) -> Result<types::PrintableString, Self::Error>;
290
291    /// Decode a `NumericString` identified by `tag` from the available input.
292    fn decode_numeric_string(
293        &mut self,
294        tag: Tag,
295        constraints: Constraints,
296    ) -> Result<types::NumericString, Self::Error>;
297
298    /// Decode a `TeletexString` identified by `tag` from the available input.
299    fn decode_teletex_string(
300        &mut self,
301        tag: Tag,
302        constraints: Constraints,
303    ) -> Result<types::TeletexString, Self::Error>;
304
305    /// Decode a `BmpString` identified by `tag` from the available input.
306    fn decode_bmp_string(
307        &mut self,
308        tag: Tag,
309        constraints: Constraints,
310    ) -> Result<types::BmpString, Self::Error>;
311
312    /// Decode an ASN.1 value that has been explicitly prefixed with `tag` from the available input.
313    fn decode_explicit_prefix<D: Decode>(&mut self, tag: Tag) -> Result<D, Self::Error>;
314    /// Decode an optional ASN.1 type that has been explicitly prefixed with `tag` from the available input.
315    fn decode_optional_with_explicit_prefix<D: Decode>(
316        &mut self,
317        tag: Tag,
318    ) -> Result<Option<D>, Self::Error>;
319    /// Decode a `UtcTime` identified by `tag` from the available input.
320    fn decode_utc_time(&mut self, tag: Tag) -> Result<types::UtcTime, Self::Error>;
321    /// Decode a `GeneralizedTime` identified by `tag` from the available input.
322    fn decode_generalized_time(&mut self, tag: Tag) -> Result<types::GeneralizedTime, Self::Error>;
323    /// Decode a 'DATE' identified by 'tag' from the available input
324    fn decode_date(&mut self, tag: Tag) -> Result<types::Date, Self::Error>;
325
326    /// Decode a `SET` identified by `tag` from the available input. Decoding
327    /// `SET`s works a little different than other methods, as you need to
328    /// provide two types `SET` and `FIELDS`, `SET` represents the complete type,
329    /// and `FIELDS` must represent a `CHOICE` with a variant for each field
330    /// from `SET`. As with `SET`s the field order is not guarenteed, so you'll
331    /// have map from `Vec<FIELDS>` to `SET` in `decode_operation`.
332    ///
333    /// Const `RC` is the count of root components in a sequence.
334    /// Const `EC` is the count of extension addition components in a sequence.
335    /// Generic `FIELDS` is the choice type, used by `F` to map the decoded field values correctly.
336    /// Generic `SET` is the set type.
337    /// Generic `D` is the closure that will decode the set by decoding the fields in the order as defined in the type.
338    /// Generic `F` is the closure that will map the `FIELDS` to the set.
339    fn decode_set<const RC: usize, const EC: usize, FIELDS, SET, D, F>(
340        &mut self,
341        tag: Tag,
342        decode_fn: D,
343        field_fn: F,
344    ) -> Result<SET, Self::Error>
345    where
346        SET: Decode + crate::types::Constructed<RC, EC>,
347        FIELDS: Decode,
348        D: Fn(&mut Self::AnyDecoder<RC, EC>, usize, Tag) -> Result<FIELDS, Self::Error>,
349        F: FnOnce(Vec<FIELDS>) -> Result<SET, Self::Error>;
350
351    /// Decode an the optional value in a `SEQUENCE` or `SET`.
352    fn decode_choice<D>(&mut self, constraints: Constraints) -> Result<D, Self::Error>
353    where
354        D: crate::types::DecodeChoice;
355
356    /// Decode an the optional value in a `SEQUENCE` or `SET`.
357    fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error>;
358
359    /// Decode an the optional value in a `SEQUENCE` or `SET` with `tag`.
360    /// Passing the correct tag is required even when used with codecs where
361    /// the tag is not present.
362    fn decode_optional_with_tag<D: Decode>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error>;
363
364    /// Decode an the optional value in a `SEQUENCE` or `SET` with `constraints`.
365    fn decode_optional_with_constraints<D: Decode>(
366        &mut self,
367        constraints: Constraints,
368    ) -> Result<Option<D>, Self::Error>;
369
370    /// Decode an the optional value in a `SEQUENCE` or `SET` with `tag`
371    /// and `constraints`.
372    fn decode_optional_with_tag_and_constraints<D: Decode>(
373        &mut self,
374        tag: Tag,
375        constraints: Constraints,
376    ) -> Result<Option<D>, Self::Error>;
377
378    /// Decode a `DEFAULT` value in a `SEQUENCE` or `SET`.
379    fn decode_default<D: Decode, F: FnOnce() -> D>(
380        &mut self,
381        default_fn: F,
382    ) -> Result<D, Self::Error> {
383        self.decode_default_with_tag(D::TAG, default_fn)
384    }
385
386    /// Decode a `DEFAULT` value in a `SEQUENCE` or `SET` with `tag` and `default_fn`.
387    fn decode_default_with_tag<D: Decode, F: FnOnce() -> D>(
388        &mut self,
389        tag: Tag,
390        default_fn: F,
391    ) -> Result<D, Self::Error> {
392        Ok(self
393            .decode_optional_with_tag::<D>(tag)?
394            .unwrap_or_else(default_fn))
395    }
396
397    /// Decode a `DEFAULT` value with constraints in a `SEQUENCE` or `SET` with a given `default_fn`.
398    fn decode_default_with_constraints<D: Decode, F: FnOnce() -> D>(
399        &mut self,
400        default_fn: F,
401        constraints: Constraints,
402    ) -> Result<D, Self::Error> {
403        Ok(self
404            .decode_optional_with_constraints::<D>(constraints)?
405            .unwrap_or_else(default_fn))
406    }
407
408    /// Decode a `DEFAULT` value in a `SEQUENCE` or `SET` with `tag`, `constraints` and `default_fn`.
409    fn decode_default_with_tag_and_constraints<D: Decode, F: FnOnce() -> D>(
410        &mut self,
411        tag: Tag,
412        default_fn: F,
413        constraints: Constraints,
414    ) -> Result<D, Self::Error> {
415        Ok(self
416            .decode_optional_with_tag_and_constraints::<D>(tag, constraints)?
417            .unwrap_or_else(default_fn))
418    }
419
420    /// Decode an extension addition value in a `SEQUENCE` or `SET`.
421    fn decode_extension_addition<D>(&mut self) -> Result<Option<D>, Self::Error>
422    where
423        D: Decode,
424    {
425        self.decode_extension_addition_with_constraints(Constraints::default())
426    }
427    /// Decode an extension addition with explicit tag in a `SEQUENCE` or `SET`.
428    fn decode_extension_addition_with_explicit_tag_and_constraints<D>(
429        &mut self,
430        tag: Tag,
431        constraints: Constraints,
432    ) -> Result<Option<D>, Self::Error>
433    where
434        D: Decode;
435
436    /// Decode an extension addition value with tag in a `SEQUENCE` or `SET`.
437    fn decode_extension_addition_with_tag<D>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error>
438    where
439        D: Decode,
440    {
441        self.decode_extension_addition_with_tag_and_constraints(tag, Constraints::default())
442    }
443    /// Decode an extension addition with constraints in a `SEQUENCE` or `SET`
444    fn decode_extension_addition_with_constraints<D>(
445        &mut self,
446        constraints: Constraints,
447    ) -> Result<Option<D>, Self::Error>
448    where
449        D: Decode,
450    {
451        self.decode_extension_addition_with_tag_and_constraints(D::TAG, constraints)
452    }
453    /// Decode a extension addition value with tag and constraints in a `SEQUENCE` or `SET`.
454    fn decode_extension_addition_with_tag_and_constraints<D>(
455        &mut self,
456        tag: Tag,
457        constraints: Constraints,
458    ) -> Result<Option<D>, Self::Error>
459    where
460        D: Decode;
461
462    /// Decode a `DEFAULT` value in a `SEQUENCE`'s or `SET`'s extension
463    fn decode_extension_addition_with_default<D: Decode, F: FnOnce() -> D>(
464        &mut self,
465        default_fn: F,
466    ) -> Result<D, Self::Error> {
467        self.decode_extension_addition_with_default_and_constraints(
468            default_fn,
469            Constraints::default(),
470        )
471    }
472    /// Decode a `DEFAULT` value with tag in a `SEQUENCE`'s or `SET`'s extension
473    fn decode_extension_addition_with_default_and_tag<D: Decode, F: FnOnce() -> D>(
474        &mut self,
475        tag: Tag,
476        default_fn: F,
477    ) -> Result<D, Self::Error> {
478        self.decode_extension_addition_with_default_and_tag_and_constraints::<D, F>(
479            tag,
480            default_fn,
481            Constraints::default(),
482        )
483    }
484
485    /// Decode a `DEFAULT` value with constraints in a `SEQUENCE`'s or `SET`'s extension
486    fn decode_extension_addition_with_default_and_constraints<D: Decode, F: FnOnce() -> D>(
487        &mut self,
488        default_fn: F,
489        constraints: Constraints,
490    ) -> Result<D, Self::Error> {
491        Ok(self
492            .decode_extension_addition_with_constraints::<D>(constraints)?
493            .unwrap_or_else(default_fn))
494    }
495    /// Decode a `DEFAULT` value with tag and constraints in a `SEQUENCE`'s or `SET`'s extension
496    fn decode_extension_addition_with_default_and_tag_and_constraints<
497        D: Decode,
498        F: FnOnce() -> D,
499    >(
500        &mut self,
501        tag: Tag,
502        default_fn: F,
503        constraints: Constraints,
504    ) -> Result<D, Self::Error> {
505        Ok(self
506            .decode_extension_addition_with_tag_and_constraints::<D>(tag, constraints)?
507            .unwrap_or_else(default_fn))
508    }
509
510    /// Decode a extension addition group in a `SEQUENCE` or `SET`.
511    ///
512    /// Const `RC` is the count of root components in a sequence.
513    /// Const `EC` is the count of extension addition components in a sequence.
514    /// Generic `D` is the type of the extension addition group.
515    fn decode_extension_addition_group<
516        const RC: usize,
517        const EC: usize,
518        D: Decode + crate::types::Constructed<RC, EC>,
519    >(
520        &mut self,
521    ) -> Result<Option<D>, Self::Error>;
522}
523
524/// A generic error that can occur while decoding ASN.1.
525/// Caller needs always to pass a `crate::Codec` variant to `Error` when implementing the decoder
526pub trait Error: core::fmt::Display {
527    /// Creates a new general error using `msg` when decoding ASN.1.
528    #[must_use]
529    fn custom<D: core::fmt::Display>(msg: D, codec: crate::Codec) -> Self;
530    /// Creates a new error about needing more data to finish parsing.
531    #[must_use]
532    fn incomplete(needed: Needed, codec: crate::Codec) -> Self;
533    /// Creates a new error about exceeding the maximum allowed data for a type.
534    #[must_use]
535    fn exceeds_max_length(length: num_bigint::BigUint, codec: crate::Codec) -> Self;
536    /// Creates a new error about a missing field.
537    #[must_use]
538    fn missing_field(name: &'static str, codec: crate::Codec) -> Self;
539    /// Creates a new error about being unable to match any variant in a choice.
540    #[must_use]
541    fn no_valid_choice(name: &'static str, codec: crate::Codec) -> Self;
542    /// Creates a new error about being unable to decode a field in a compound
543    /// type, such as a set or sequence.
544    #[must_use]
545    fn field_error(name: &'static str, error: DecodeError, codec: crate::Codec) -> Self;
546    /// Creates a new error about finding a duplicate field.
547    #[must_use]
548    fn duplicate_field(name: &'static str, codec: crate::Codec) -> Self;
549    /// Create a new error about unknown field.
550    #[must_use]
551    fn unknown_field(index: usize, tag: Tag, codec: crate::Codec) -> Self;
552}
553
554impl Decode for () {
555    fn decode_with_tag_and_constraints<D: Decoder>(
556        decoder: &mut D,
557        tag: Tag,
558        _: Constraints,
559    ) -> Result<Self, D::Error> {
560        decoder.decode_null(tag)
561    }
562}
563
564impl<D: Decode> Decode for Option<D> {
565    fn decode<DE: Decoder>(decoder: &mut DE) -> Result<Self, DE::Error> {
566        decoder.decode_optional()
567    }
568
569    fn decode_with_tag<DE: Decoder>(decoder: &mut DE, tag: Tag) -> Result<Self, DE::Error> {
570        decoder.decode_optional_with_tag(tag)
571    }
572
573    fn decode_with_constraints<DE: Decoder>(
574        decoder: &mut DE,
575        constraints: Constraints,
576    ) -> Result<Self, DE::Error> {
577        decoder.decode_optional_with_constraints(constraints)
578    }
579
580    fn decode_with_tag_and_constraints<DE: Decoder>(
581        decoder: &mut DE,
582        tag: Tag,
583        constraints: Constraints,
584    ) -> Result<Self, DE::Error> {
585        decoder.decode_optional_with_tag_and_constraints(tag, constraints)
586    }
587}
588
589impl Decode for bool {
590    fn decode_with_tag_and_constraints<D: Decoder>(
591        decoder: &mut D,
592        tag: Tag,
593        _: Constraints,
594    ) -> Result<Self, D::Error> {
595        decoder.decode_bool(tag)
596    }
597}
598
599macro_rules! impl_integers {
600    ($($int:ty),+ $(,)?) => {
601        $(
602        impl Decode for $int {
603            fn decode_with_tag_and_constraints<D: Decoder>(decoder: &mut D, tag: Tag, constraints: Constraints) -> Result<Self, D::Error> {
604                decoder.decode_integer::<$int>(tag, constraints)
605            }
606        }
607        )+
608    }
609}
610
611impl_integers! {
612    i8,
613    i16,
614    i32,
615    i64,
616    i128,
617    isize,
618    u8,
619    u16,
620    u32,
621    u64,
622    // TODO cannot support u128 as it is constrained type by default and current constraints uses i128 for bounds
623    // u128,
624    usize,
625    BigInt
626}
627
628impl<const START: i128, const END: i128> Decode for types::ConstrainedInteger<START, END> {
629    fn decode_with_tag_and_constraints<D: Decoder>(
630        decoder: &mut D,
631        tag: Tag,
632        constraints: Constraints,
633    ) -> Result<Self, D::Error> {
634        decoder
635            .decode_integer::<types::Integer>(tag, constraints)
636            .map(Self)
637    }
638}
639
640impl Decode for types::Integer {
641    fn decode_with_tag_and_constraints<D: Decoder>(
642        decoder: &mut D,
643        tag: Tag,
644        constraints: Constraints,
645    ) -> Result<Self, D::Error> {
646        decoder.decode_integer::<types::Integer>(tag, constraints)
647    }
648}
649
650#[cfg(feature = "f32")]
651impl Decode for f32 {
652    fn decode_with_tag_and_constraints<D: Decoder>(
653        decoder: &mut D,
654        tag: Tag,
655        _: Constraints,
656    ) -> Result<Self, D::Error> {
657        decoder.decode_real::<f32>(tag, Constraints::default())
658    }
659}
660
661#[cfg(feature = "f64")]
662impl Decode for f64 {
663    fn decode_with_tag_and_constraints<D: Decoder>(
664        decoder: &mut D,
665        tag: Tag,
666        _: Constraints,
667    ) -> Result<Self, D::Error> {
668        decoder.decode_real::<f64>(tag, Constraints::default())
669    }
670}
671
672impl<T: Decode> Decode for Box<T> {
673    fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, D::Error> {
674        T::decode(decoder).map(Box::new)
675    }
676
677    fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
678        T::decode_with_tag(decoder, tag).map(Box::new)
679    }
680
681    fn decode_with_constraints<DE: Decoder>(
682        decoder: &mut DE,
683        constraints: Constraints,
684    ) -> Result<Self, DE::Error> {
685        T::decode_with_constraints(decoder, constraints).map(Box::new)
686    }
687
688    fn decode_with_tag_and_constraints<DE: Decoder>(
689        decoder: &mut DE,
690        tag: Tag,
691        constraints: Constraints,
692    ) -> Result<Self, DE::Error> {
693        T::decode_with_tag_and_constraints(decoder, tag, constraints).map(Box::new)
694    }
695}
696
697impl Decode for types::OctetString {
698    fn decode_with_tag_and_constraints<D: Decoder>(
699        decoder: &mut D,
700        tag: Tag,
701        constraints: Constraints,
702    ) -> Result<Self, D::Error> {
703        decoder
704            .decode_octet_string::<Vec<u8>>(tag, constraints)
705            .map(Into::into)
706    }
707}
708
709impl Decode for types::ObjectIdentifier {
710    fn decode_with_tag_and_constraints<D: Decoder>(
711        decoder: &mut D,
712        tag: Tag,
713        _: Constraints,
714    ) -> Result<Self, D::Error> {
715        decoder.decode_object_identifier(tag)
716    }
717}
718
719impl Decode for types::Utf8String {
720    fn decode_with_tag_and_constraints<D: Decoder>(
721        decoder: &mut D,
722        tag: Tag,
723        constraints: Constraints,
724    ) -> Result<Self, D::Error> {
725        decoder.decode_utf8_string(tag, constraints)
726    }
727}
728
729impl Decode for types::UtcTime {
730    fn decode_with_tag_and_constraints<D: Decoder>(
731        decoder: &mut D,
732        tag: Tag,
733        _: Constraints,
734    ) -> Result<Self, D::Error> {
735        decoder.decode_utc_time(tag)
736    }
737}
738
739impl Decode for types::GeneralizedTime {
740    fn decode_with_tag_and_constraints<D: Decoder>(
741        decoder: &mut D,
742        tag: Tag,
743        _: Constraints,
744    ) -> Result<Self, D::Error> {
745        decoder.decode_generalized_time(tag)
746    }
747}
748
749impl Decode for types::Any {
750    fn decode_with_tag_and_constraints<D: Decoder>(
751        decoder: &mut D,
752        _: Tag,
753        _: Constraints,
754    ) -> Result<Self, D::Error> {
755        decoder.decode_any()
756    }
757}
758
759impl<T: Decode> Decode for alloc::vec::Vec<T> {
760    fn decode_with_tag_and_constraints<D: Decoder>(
761        decoder: &mut D,
762        tag: Tag,
763        constraints: Constraints,
764    ) -> Result<Self, D::Error> {
765        decoder.decode_sequence_of(tag, constraints)
766    }
767}
768
769impl<T: Decode + Eq + core::hash::Hash> Decode for SetOf<T> {
770    fn decode_with_tag_and_constraints<D: Decoder>(
771        decoder: &mut D,
772        tag: Tag,
773        constraints: Constraints,
774    ) -> Result<Self, D::Error> {
775        decoder.decode_set_of(tag, constraints)
776    }
777}
778
779impl<T: Decode, const N: usize> Decode for [T; N] {
780    fn decode_with_tag_and_constraints<D: Decoder>(
781        decoder: &mut D,
782        tag: Tag,
783        constraints: Constraints,
784    ) -> Result<Self, D::Error> {
785        let sequence = decoder.decode_sequence_of(tag, constraints)?;
786        sequence.try_into().map_err(|seq: Vec<_>| {
787            D::Error::from(DecodeError::incorrect_item_number_in_sequence(
788                N,
789                seq.len(),
790                decoder.codec(),
791            ))
792        })
793    }
794}
795
796impl<T: AsnType, V: Decode> Decode for types::Implicit<T, V> {
797    fn decode_with_tag_and_constraints<D: Decoder>(
798        decoder: &mut D,
799        tag: Tag,
800        constraints: Constraints,
801    ) -> Result<Self, D::Error> {
802        Ok(Self::new(V::decode_with_tag_and_constraints(
803            decoder,
804            tag,
805            constraints,
806        )?))
807    }
808}
809
810impl<T: AsnType, V: Decode> Decode for types::Explicit<T, V> {
811    fn decode_with_tag_and_constraints<D: Decoder>(
812        decoder: &mut D,
813        tag: Tag,
814        _: Constraints,
815    ) -> Result<Self, D::Error> {
816        Ok(Self::new(decoder.decode_explicit_prefix(tag)?))
817    }
818}
819impl<T: AsnType> Decode for core::marker::PhantomData<T> {
820    fn decode_with_tag_and_constraints<D: Decoder>(
821        _: &mut D,
822        _: Tag,
823        _: Constraints,
824    ) -> Result<Self, D::Error> {
825        Ok(core::marker::PhantomData)
826    }
827}