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