rasn/
de.rs

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