1use 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#[must_use]
14pub fn iter<D: Decode>(input: &[u8], codec: crate::codec::Codec) -> Iter<'_, D> {
15 Iter::new(input, codec)
16}
17
18enum IterBuffer<'a> {
23 Borrowed(&'a [u8]),
24 Owned { data: Vec<u8>, pos: usize },
25}
26
27impl IterBuffer<'_> {
28 fn as_slice(&self) -> &[u8] {
30 match self {
31 IterBuffer::Borrowed(slice) => slice,
32 IterBuffer::Owned { data, pos } => &data[*pos..],
33 }
34 }
35 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 if *pos > data.len() / 2 {
43 data.drain(0..*pos);
44 *pos = 0;
45 }
46 }
47 }
48 }
49
50 #[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 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
70pub 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 #[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 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 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
112pub trait Decode: Sized + AsnType {
114 fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, D::Error> {
123 Self::decode_with_tag(decoder, Self::TAG)
124 }
125
126 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 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 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
161pub trait Decoder<const RCL: usize = 0, const ECL: usize = 0>: Sized {
166 type Ok;
168 type Error: Error + Into<crate::error::DecodeError> + From<crate::error::DecodeError>;
170 type AnyDecoder<const R: usize, const E: usize>: Decoder<RCL, ECL, Ok = Self::Ok, Error = Self::Error>
172 + Decoder;
173
174 #[must_use]
176 fn codec(&self) -> crate::Codec;
177
178 fn decode_any(&mut self) -> Result<types::Any, Self::Error>;
180 fn decode_bit_string(
182 &mut self,
183 tag: Tag,
184 constraints: Constraints,
185 ) -> Result<types::BitString, Self::Error>;
186 fn decode_bool(&mut self, tag: Tag) -> Result<bool, Self::Error>;
188 fn decode_enumerated<E: Enumerated>(&mut self, tag: Tag) -> Result<E, Self::Error>;
190 fn decode_integer<I: types::IntegerType>(
192 &mut self,
193 tag: Tag,
194 constraints: Constraints,
195 ) -> Result<I, Self::Error>;
196
197 fn decode_real<R: types::RealType>(
199 &mut self,
200 tag: Tag,
201 constraints: Constraints,
202 ) -> Result<R, Self::Error>;
203
204 fn decode_null(&mut self, tag: Tag) -> Result<(), Self::Error>;
206 fn decode_object_identifier(
208 &mut self,
209 tag: Tag,
210 ) -> Result<types::ObjectIdentifier, Self::Error>;
211 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 fn decode_sequence_of<D: Decode>(
232 &mut self,
233 tag: Tag,
234 constraints: Constraints,
235 ) -> Result<Vec<D>, Self::Error>;
236 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 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 fn decode_utf8_string(
253 &mut self,
254 tag: Tag,
255 constraints: Constraints,
256 ) -> Result<types::Utf8String, Self::Error>;
257
258 fn decode_visible_string(
260 &mut self,
261 tag: Tag,
262 constraints: Constraints,
263 ) -> Result<types::VisibleString, Self::Error>;
264
265 fn decode_general_string(
267 &mut self,
268 tag: Tag,
269 constraints: Constraints,
270 ) -> Result<types::GeneralString, Self::Error>;
271
272 fn decode_graphic_string(
274 &mut self,
275 tag: Tag,
276 constraints: Constraints,
277 ) -> Result<types::GraphicString, Self::Error>;
278
279 fn decode_ia5_string(
281 &mut self,
282 tag: Tag,
283 constraints: Constraints,
284 ) -> Result<types::Ia5String, Self::Error>;
285
286 fn decode_printable_string(
288 &mut self,
289 tag: Tag,
290 constraints: Constraints,
291 ) -> Result<types::PrintableString, Self::Error>;
292
293 fn decode_numeric_string(
295 &mut self,
296 tag: Tag,
297 constraints: Constraints,
298 ) -> Result<types::NumericString, Self::Error>;
299
300 fn decode_teletex_string(
302 &mut self,
303 tag: Tag,
304 constraints: Constraints,
305 ) -> Result<types::TeletexString, Self::Error>;
306
307 fn decode_bmp_string(
309 &mut self,
310 tag: Tag,
311 constraints: Constraints,
312 ) -> Result<types::BmpString, Self::Error>;
313
314 fn decode_explicit_prefix<D: Decode>(&mut self, tag: Tag) -> Result<D, Self::Error>;
316 fn decode_optional_with_explicit_prefix<D: Decode>(
318 &mut self,
319 tag: Tag,
320 ) -> Result<Option<D>, Self::Error>;
321 fn decode_utc_time(&mut self, tag: Tag) -> Result<types::UtcTime, Self::Error>;
323 fn decode_generalized_time(&mut self, tag: Tag) -> Result<types::GeneralizedTime, Self::Error>;
325 fn decode_date(&mut self, tag: Tag) -> Result<types::Date, Self::Error>;
327
328 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 fn decode_choice<D>(&mut self, constraints: Constraints) -> Result<D, Self::Error>
355 where
356 D: crate::types::DecodeChoice;
357
358 fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error>;
360
361 fn decode_optional_with_tag<D: Decode>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error>;
365
366 fn decode_optional_with_constraints<D: Decode>(
368 &mut self,
369 constraints: Constraints,
370 ) -> Result<Option<D>, Self::Error>;
371
372 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
526pub trait Error: core::fmt::Display {
529 #[must_use]
531 fn custom<D: core::fmt::Display>(msg: D, codec: crate::Codec) -> Self;
532 #[must_use]
534 fn incomplete(needed: Needed, codec: crate::Codec) -> Self;
535 #[must_use]
537 fn exceeds_max_length(length: num_bigint::BigUint, codec: crate::Codec) -> Self;
538 #[must_use]
540 fn missing_field(name: &'static str, codec: crate::Codec) -> Self;
541 #[must_use]
543 fn no_valid_choice(name: &'static str, codec: crate::Codec) -> Self;
544 #[must_use]
547 fn field_error(name: &'static str, error: DecodeError, codec: crate::Codec) -> Self;
548 #[must_use]
550 fn duplicate_field(name: &'static str, codec: crate::Codec) -> Self;
551 #[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 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}