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
12pub fn iter<D: Decode>(input: &[u8], codec: crate::codec::Codec) -> Iter<'_, D> {
14 Iter::new(input, codec)
15}
16
17enum IterBuffer<'a> {
22 Borrowed(&'a [u8]),
23 Owned { data: Vec<u8>, pos: usize },
24}
25
26impl IterBuffer<'_> {
27 fn as_slice(&self) -> &[u8] {
29 match self {
30 IterBuffer::Borrowed(slice) => slice,
31 IterBuffer::Owned { data, pos } => &data[*pos..],
32 }
33 }
34 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 if *pos > data.len() / 2 {
42 data.drain(0..*pos);
43 *pos = 0;
44 }
45 }
46 }
47 }
48
49 #[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 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
69pub 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 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 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 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
110pub trait Decode: Sized + AsnType {
112 fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, D::Error> {
121 Self::decode_with_tag(decoder, Self::TAG)
122 }
123
124 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 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 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
159pub trait Decoder<const RCL: usize = 0, const ECL: usize = 0>: Sized {
164 type Ok;
166 type Error: Error + Into<crate::error::DecodeError> + From<crate::error::DecodeError>;
168 type AnyDecoder<const R: usize, const E: usize>: Decoder<RCL, ECL, Ok = Self::Ok, Error = Self::Error>
170 + Decoder;
171
172 #[must_use]
174 fn codec(&self) -> crate::Codec;
175
176 fn decode_any(&mut self) -> Result<types::Any, Self::Error>;
178 fn decode_bit_string(
180 &mut self,
181 tag: Tag,
182 constraints: Constraints,
183 ) -> Result<types::BitString, Self::Error>;
184 fn decode_bool(&mut self, tag: Tag) -> Result<bool, Self::Error>;
186 fn decode_enumerated<E: Enumerated>(&mut self, tag: Tag) -> Result<E, Self::Error>;
188 fn decode_integer<I: types::IntegerType>(
190 &mut self,
191 tag: Tag,
192 constraints: Constraints,
193 ) -> Result<I, Self::Error>;
194
195 fn decode_real<R: types::RealType>(
197 &mut self,
198 tag: Tag,
199 constraints: Constraints,
200 ) -> Result<R, Self::Error>;
201
202 fn decode_null(&mut self, tag: Tag) -> Result<(), Self::Error>;
204 fn decode_object_identifier(
206 &mut self,
207 tag: Tag,
208 ) -> Result<types::ObjectIdentifier, Self::Error>;
209 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 fn decode_sequence_of<D: Decode>(
230 &mut self,
231 tag: Tag,
232 constraints: Constraints,
233 ) -> Result<Vec<D>, Self::Error>;
234 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 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 fn decode_utf8_string(
251 &mut self,
252 tag: Tag,
253 constraints: Constraints,
254 ) -> Result<types::Utf8String, Self::Error>;
255
256 fn decode_visible_string(
258 &mut self,
259 tag: Tag,
260 constraints: Constraints,
261 ) -> Result<types::VisibleString, Self::Error>;
262
263 fn decode_general_string(
265 &mut self,
266 tag: Tag,
267 constraints: Constraints,
268 ) -> Result<types::GeneralString, Self::Error>;
269
270 fn decode_graphic_string(
272 &mut self,
273 tag: Tag,
274 constraints: Constraints,
275 ) -> Result<types::GraphicString, Self::Error>;
276
277 fn decode_ia5_string(
279 &mut self,
280 tag: Tag,
281 constraints: Constraints,
282 ) -> Result<types::Ia5String, Self::Error>;
283
284 fn decode_printable_string(
286 &mut self,
287 tag: Tag,
288 constraints: Constraints,
289 ) -> Result<types::PrintableString, Self::Error>;
290
291 fn decode_numeric_string(
293 &mut self,
294 tag: Tag,
295 constraints: Constraints,
296 ) -> Result<types::NumericString, Self::Error>;
297
298 fn decode_teletex_string(
300 &mut self,
301 tag: Tag,
302 constraints: Constraints,
303 ) -> Result<types::TeletexString, Self::Error>;
304
305 fn decode_bmp_string(
307 &mut self,
308 tag: Tag,
309 constraints: Constraints,
310 ) -> Result<types::BmpString, Self::Error>;
311
312 fn decode_explicit_prefix<D: Decode>(&mut self, tag: Tag) -> Result<D, Self::Error>;
314 fn decode_optional_with_explicit_prefix<D: Decode>(
316 &mut self,
317 tag: Tag,
318 ) -> Result<Option<D>, Self::Error>;
319 fn decode_utc_time(&mut self, tag: Tag) -> Result<types::UtcTime, Self::Error>;
321 fn decode_generalized_time(&mut self, tag: Tag) -> Result<types::GeneralizedTime, Self::Error>;
323 fn decode_date(&mut self, tag: Tag) -> Result<types::Date, Self::Error>;
325
326 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 fn decode_choice<D>(&mut self, constraints: Constraints) -> Result<D, Self::Error>
353 where
354 D: crate::types::DecodeChoice;
355
356 fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error>;
358
359 fn decode_optional_with_tag<D: Decode>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error>;
363
364 fn decode_optional_with_constraints<D: Decode>(
366 &mut self,
367 constraints: Constraints,
368 ) -> Result<Option<D>, Self::Error>;
369
370 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
524pub trait Error: core::fmt::Display {
527 #[must_use]
529 fn custom<D: core::fmt::Display>(msg: D, codec: crate::Codec) -> Self;
530 #[must_use]
532 fn incomplete(needed: Needed, codec: crate::Codec) -> Self;
533 #[must_use]
535 fn exceeds_max_length(length: num_bigint::BigUint, codec: crate::Codec) -> Self;
536 #[must_use]
538 fn missing_field(name: &'static str, codec: crate::Codec) -> Self;
539 #[must_use]
541 fn no_valid_choice(name: &'static str, codec: crate::Codec) -> Self;
542 #[must_use]
545 fn field_error(name: &'static str, error: DecodeError, codec: crate::Codec) -> Self;
546 #[must_use]
548 fn duplicate_field(name: &'static str, codec: crate::Codec) -> Self;
549 #[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 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}