1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
#[cfg(feature = "jer")]
use core::num::ParseIntError;

use super::strings::PermittedAlphabetError;
use alloc::{boxed::Box, string::ToString};

#[cfg(feature = "jer")]
use jzon::JsonValue;
use snafu::Snafu;
#[cfg(feature = "backtraces")]
use snafu::{Backtrace, GenerateImplicitData};

use crate::de::Error;
use crate::types::{constraints::Bounded, variants::Variants, Tag};
use crate::Codec;
use num_bigint::BigInt;

/// Variants for every codec-specific `DecodeError` kind.
#[derive(Debug)]
#[non_exhaustive]
pub enum CodecDecodeError {
    Ber(BerDecodeErrorKind),
    Cer(CerDecodeErrorKind),
    Der(DerDecodeErrorKind),
    Uper(UperDecodeErrorKind),
    Aper(AperDecodeErrorKind),
    #[cfg(feature = "jer")]
    Jer(JerDecodeErrorKind),
    Oer(OerDecodeErrorKind),
    Coer(CoerDecodeErrorKind),
}

macro_rules! impl_from {
    ($variant:ident, $error_kind:ty) => {
        impl From<$error_kind> for DecodeError {
            fn from(error: $error_kind) -> Self {
                Self::from_codec_kind(CodecDecodeError::$variant(error))
            }
        }
    };
}

// implement From for each variant of CodecDecodeError into DecodeError
impl_from!(Ber, BerDecodeErrorKind);
impl_from!(Cer, CerDecodeErrorKind);
impl_from!(Der, DerDecodeErrorKind);
impl_from!(Uper, UperDecodeErrorKind);
impl_from!(Aper, AperDecodeErrorKind);
#[cfg(feature = "jer")]
impl_from!(Jer, JerDecodeErrorKind);
impl_from!(Oer, OerDecodeErrorKind);
impl_from!(Coer, CoerDecodeErrorKind);

impl From<CodecDecodeError> for DecodeError {
    fn from(error: CodecDecodeError) -> Self {
        Self::from_codec_kind(error)
    }
}

/// An error type for failed decoding for every decoder.
/// Abstracts over the different generic and codec-specific errors.
///
/// `kind` field is used to determine the kind of error that occurred.
/// `codec` field is used to determine the codec that failed.
/// `backtrace` field is used to determine the backtrace of the error.
///
/// There is `Kind::CodecSpecific` variant which wraps the codec-specific
/// errors as `CodecEncodeError` type.
///
/// # Example
/// ```rust
/// use nom::Needed;
/// use rasn::codec::Codec;
/// use rasn::error::DecodeErrorKind;
/// use rasn::prelude::*;
///
/// #[derive(AsnType, Clone, Debug, Decode, Encode, PartialEq)]
/// #[rasn(delegate)]
/// struct MyString(pub VisibleString);
///
/// fn main() {
///     // Hello, World! in decimal bytes with trailing zeros
///     // Below sample requires that `backtraces` feature is enabled
///     let hello_data = vec![
///         13, 145, 151, 102, 205, 235, 16, 119, 223, 203, 102, 68, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
///         0,
///     ];
///     // Initially parse the first 2 bytes for Error demonstration purposes
///     let mut total = 2;
///
///     loop {
///         let decoded = Codec::Uper.decode_from_binary::<MyString>(&hello_data[0..hello_data.len().min(total)]);
///         match decoded {
///             Ok(succ) => {
///                 println!("Successful decoding!");
///                 println!("Decoded string: {}", succ.0);
///                 break;
///             }
///             Err(e) => {
///                 // e is DecodeError, kind is boxed
///                 match *e.kind {
///                     DecodeErrorKind::Incomplete { needed } => {
///                         println!("Codec error source: {}", e.codec);
///                         println!("Error kind: {}", e.kind);
///                         // Here you need to know, that VisibleString has width of 7 bits and UPER parses input
///                         // as bits, if you want to build logic around it, and feed exactly the correct amount of data.
///                         // Usually you might need to just provide one byte at time instead when something is missing, since
///                         // inner logic might not be known to you, and data structures can get complex.
///                         total += match needed {
///                             Needed::Size(n) => {
///                                 let missing_bytes = n.get() / 7;
///                                 missing_bytes
///
///                             }
///                             _ => {
///                                 #[cfg(feature = "backtraces")]
///                                 println!("Backtrace:\n{:?}", e.backtrace);
///                                 panic!("Unexpected error! {e:?}");
///                             }
///                         }
///                     }
///                     k => {
///                         #[cfg(feature = "backtraces")]
///                         println!("Backtrace:\n{:?}", e.backtrace);
///                         panic!("Unexpected error! {k:?}");
///                     }
///                 }
///             }
///         }
///     }
/// }
///```
/// The previous will produce something like following:
/// ```text
/// Codec error: UPER
/// Error kind: Need more BITS to continue: (Size(83)).
/// Successful decoding!
/// Decoded string: Hello, world!
/// ```
#[derive(Debug)]
#[allow(clippy::module_name_repetitions)]
pub struct DecodeError {
    pub kind: Box<DecodeErrorKind>,
    pub codec: Codec,
    #[cfg(feature = "backtraces")]
    pub backtrace: Backtrace,
}
impl core::fmt::Display for DecodeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        writeln!(f, "Error Kind: {}", self.kind)?;
        writeln!(f, "Codec: {}", self.codec)?;
        #[cfg(feature = "backtraces")]
        write!(f, "\nBacktrace:\n{}", self.backtrace)?;
        Ok(())
    }
}

impl DecodeError {
    #[must_use]
    pub fn permitted_alphabet_error(reason: PermittedAlphabetError, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::PermittedAlphabetError { reason }, codec)
    }
    #[must_use]
    pub fn size_constraint_not_satisfied(
        size: Option<usize>,
        expected: alloc::string::String,
        codec: Codec,
    ) -> Self {
        Self::from_kind(
            DecodeErrorKind::SizeConstraintNotSatisfied { size, expected },
            codec,
        )
    }
    #[must_use]
    pub fn value_constraint_not_satisfied(
        value: BigInt,
        expected: Bounded<i128>,
        codec: Codec,
    ) -> Self {
        Self::from_kind(
            DecodeErrorKind::ValueConstraintNotSatisfied { value, expected },
            codec,
        )
    }
    #[must_use]
    pub fn discriminant_value_not_found(discriminant: isize, codec: Codec) -> Self {
        Self::from_kind(
            DecodeErrorKind::DiscriminantValueNotFound { discriminant },
            codec,
        )
    }
    #[must_use]
    pub fn range_exceeds_platform_width(needed: u32, present: u32, codec: Codec) -> Self {
        Self::from_kind(
            DecodeErrorKind::RangeExceedsPlatformWidth { needed, present },
            codec,
        )
    }
    #[must_use]
    pub fn fixed_string_conversion_failed(
        tag: Tag,
        actual: usize,
        expected: usize,
        codec: Codec,
    ) -> Self {
        Self::from_kind(
            DecodeErrorKind::FixedStringConversionFailed {
                tag,
                actual,
                expected,
            },
            codec,
        )
    }
    #[must_use]
    pub fn incorrect_item_number_in_sequence(expected: usize, actual: usize, codec: Codec) -> Self {
        Self::from_kind(
            DecodeErrorKind::IncorrectItemNumberInSequence { expected, actual },
            codec,
        )
    }
    #[must_use]
    pub fn integer_overflow(max_width: u32, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::IntegerOverflow { max_width }, codec)
    }
    #[must_use]
    pub fn integer_type_conversion_failed(msg: alloc::string::String, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::IntegerTypeConversionFailed { msg }, codec)
    }
    #[must_use]
    pub fn invalid_bit_string(bits: u8, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::InvalidBitString { bits }, codec)
    }
    #[must_use]
    pub fn missing_tag_class_or_value_in_sequence_or_set(
        class: crate::types::Class,
        value: u32,
        codec: Codec,
    ) -> Self {
        Self::from_kind(
            DecodeErrorKind::MissingTagClassOrValueInSequenceOrSet { class, value },
            codec,
        )
    }

    #[must_use]
    pub fn type_not_extensible(codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::TypeNotExtensible, codec)
    }
    #[must_use]
    pub fn parser_fail(msg: alloc::string::String, codec: Codec) -> Self {
        DecodeError::from_kind(DecodeErrorKind::Parser { msg }, codec)
    }

    #[must_use]
    pub fn required_extension_not_present(tag: Tag, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::RequiredExtensionNotPresent { tag }, codec)
    }

    #[must_use]
    pub fn enumeration_index_not_found(index: usize, extended_list: bool, codec: Codec) -> Self {
        Self::from_kind(
            DecodeErrorKind::EnumerationIndexNotFound {
                index,
                extended_list,
            },
            codec,
        )
    }
    #[must_use]
    pub fn choice_index_exceeds_platform_width(
        needed: u32,
        present: DecodeError,
        codec: Codec,
    ) -> Self {
        Self::from_kind(
            DecodeErrorKind::ChoiceIndexExceedsPlatformWidth { needed, present },
            codec,
        )
    }
    #[must_use]
    pub fn length_exceeds_platform_width(msg: alloc::string::String, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::LengthExceedsPlatformWidth { msg }, codec)
    }

    #[must_use]
    pub fn choice_index_not_found(index: usize, variants: Variants, codec: Codec) -> Self {
        Self::from_kind(
            DecodeErrorKind::ChoiceIndexNotFound { index, variants },
            codec,
        )
    }
    #[must_use]
    pub fn string_conversion_failed(tag: Tag, msg: alloc::string::String, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::StringConversionFailed { tag, msg }, codec)
    }
    #[must_use]
    pub fn unexpected_extra_data(length: usize, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::UnexpectedExtraData { length }, codec)
    }
    #[must_use]
    pub fn unexpected_empty_input(codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::UnexpectedEmptyInput, codec)
    }

    pub fn assert_length(
        expected: usize,
        actual: usize,
        codec: Codec,
    ) -> core::result::Result<(), DecodeError> {
        if expected == actual {
            Ok(())
        } else {
            Err(DecodeError::from_kind(
                DecodeErrorKind::MismatchedLength { expected, actual },
                codec,
            ))
        }
    }

    pub fn map_nom_err<T: core::fmt::Debug>(
        error: nom::Err<nom::error::Error<T>>,
        codec: Codec,
    ) -> DecodeError {
        let msg = match error {
            nom::Err::Incomplete(needed) => return DecodeError::incomplete(needed, codec),
            err => alloc::format!("Parsing Failure: {err}"),
        };
        DecodeError::parser_fail(msg, codec)
    }
    #[must_use]
    pub fn from_kind(kind: DecodeErrorKind, codec: Codec) -> Self {
        Self {
            kind: Box::new(kind),
            codec,
            #[cfg(feature = "backtraces")]
            backtrace: Backtrace::generate(),
        }
    }
    #[must_use]
    fn from_codec_kind(inner: CodecDecodeError) -> Self {
        let codec = match inner {
            CodecDecodeError::Ber(_) => crate::Codec::Ber,
            CodecDecodeError::Cer(_) => crate::Codec::Cer,
            CodecDecodeError::Der(_) => crate::Codec::Der,
            CodecDecodeError::Uper(_) => crate::Codec::Uper,
            CodecDecodeError::Aper(_) => crate::Codec::Aper,
            #[cfg(feature = "jer")]
            CodecDecodeError::Jer(_) => crate::Codec::Jer,
            CodecDecodeError::Oer(_) => crate::Codec::Oer,
            CodecDecodeError::Coer(_) => crate::Codec::Coer,
        };
        Self {
            kind: Box::new(DecodeErrorKind::CodecSpecific { inner }),
            codec,
            #[cfg(feature = "backtraces")]
            backtrace: Backtrace::generate(),
        }
    }
}

/// `DecodeError` kinds which are common for all codecs.
#[derive(Snafu)]
#[snafu(visibility(pub))]
#[derive(Debug)]
#[non_exhaustive]
pub enum DecodeErrorKind {
    #[snafu(display("Alphabet constraint not satisfied {}", reason))]
    PermittedAlphabetError { reason: PermittedAlphabetError },
    #[snafu(display("Size constraint not satisfied: expected: {expected}; actual: {size:?}"))]
    SizeConstraintNotSatisfied {
        /// Actual sie of the data
        size: Option<usize>,
        /// Expected size by the constraint
        expected: alloc::string::String,
    },
    #[snafu(display("Value constraint not satisfied: expected: {expected}; actual: {value}"))]
    ValueConstraintNotSatisfied {
        /// Actual value of the data
        value: BigInt,
        /// Expected value by the constraint
        expected: Bounded<i128>,
    },
    #[snafu(display("Wrapped codec-specific decode error"))]
    CodecSpecific { inner: CodecDecodeError },

    #[snafu(display(
        "Enumeration index '{}' did not match any variant. Extended list: {}",
        index,
        extended_list
    ))]
    EnumerationIndexNotFound {
        /// The found index of the enumerated variant.
        index: usize,
        /// Whether the index was checked from the extended variants.
        extended_list: bool,
    },
    #[snafu(display("choice index '{index}' did not match any variant"))]
    ChoiceIndexNotFound {
        /// The found index of the choice variant.
        index: usize,
        /// The variants checked for presence.
        variants: Variants,
    },
    #[snafu(display("integer range larger than possible to address on this platform. needed: {needed} present: {present}"))]
    ChoiceIndexExceedsPlatformWidth {
        /// Amount of bytes needed.
        needed: u32,
        /// Inner error
        present: DecodeError,
    },
    #[snafu(display("Custom: {}", msg))]
    Custom {
        /// The error's message.
        msg: alloc::string::String,
    },
    #[snafu(display("Discriminant value '{}' did not match any variant", discriminant))]
    DiscriminantValueNotFound {
        /// The found value of the discriminant
        discriminant: isize,
    },
    #[snafu(display("Duplicate field for `{}`", name))]
    DuplicateField {
        /// The field's name.
        name: &'static str,
    },
    #[snafu(display("Expected maximum of {} items", length))]
    ExceedsMaxLength {
        /// The maximum length.
        length: num_bigint::BigUint,
    },
    ///  More than `usize::MAX` number of data requested.
    #[snafu(display(
        "Length of the incoming data is either incorrect or your device is up by miracle."
    ))]
    LengthExceedsPlatformWidth { msg: alloc::string::String },
    #[snafu(display("Error when decoding field `{}`: {}", name, nested))]
    FieldError {
        /// The field's name.
        name: &'static str,
        nested: Box<DecodeError>,
    },
    /// Input is provided as BIT slice for nom in UPER/APER.
    /// On BER/CER/DER it is as BYTE slice.
    /// Hence, `needed` field can describe either bits or bytes depending on the codec.
    #[snafu(display("Need more BITS to continue: ({:?}).", needed))]
    Incomplete {
        /// Amount of bits/bytes needed.
        needed: nom::Needed,
    },
    #[snafu(display(
        "Invalid item number in Sequence: expected {}, actual {}",
        expected,
        actual
    ))]
    IncorrectItemNumberInSequence {
        /// The expected item number.
        expected: usize,
        /// The actual item number.
        actual: usize,
    },
    #[snafu(display("Actual integer larger than expected {} bits", max_width))]
    IntegerOverflow {
        /// The maximum integer width.
        max_width: u32,
    },
    #[snafu(display("Failed to cast integer to another integer type: {msg} "))]
    IntegerTypeConversionFailed { msg: alloc::string::String },
    #[snafu(display("BitString contains an invalid amount of unused bits: {}", bits))]
    InvalidBitString {
        /// The amount of invalid bits.
        bits: u8,
    },
    /// BOOL value is not `0` or `0xFF`. Applies: BER/COER/PER? TODO categorize better
    #[snafu(display(
        "Bool value is not `0` or `0xFF` as canonical requires. Actual: {}",
        value
    ))]
    InvalidBool { value: u8 },
    // Length of Length zero
    #[snafu(display("Length of Length cannot be zero"))]
    ZeroLengthOfLength,
    /// The length does not match what was expected.
    #[snafu(display("Expected {:?} bytes, actual length: {:?}", expected, actual))]
    MismatchedLength {
        /// The expected length.
        expected: usize,
        /// The actual length.
        actual: usize,
    },

    #[snafu(display("Missing field `{}`", name))]
    MissingField {
        /// The field's name.
        name: &'static str,
    },
    #[snafu(display("Expected class: {}, value: {} in sequence or set Missing tag class or value in sequence or set", class, value))]
    MissingTagClassOrValueInSequenceOrSet {
        /// The field's name.
        class: crate::types::Class,
        value: u32,
    },

    #[snafu(display("integer range larger than possible to address on this platform. needed: {needed} present: {present}"))]
    RangeExceedsPlatformWidth {
        /// Amount of bytes needed.
        needed: u32,
        /// Amount of bytes needed.
        present: u32,
    },
    #[snafu(display("Extension with class `{}` and tag `{}` required, but not present", tag.class, tag.value))]
    RequiredExtensionNotPresent { tag: crate::types::Tag },
    #[snafu(display("Extension {} required but not present", tag.class))]
    ExtensionRequiredButNotPresent { tag: crate::types::Tag },
    #[snafu(display("Error in Parser: {}", msg))]
    Parser {
        /// The error's message.
        msg: alloc::string::String,
    },
    #[snafu(display(
        "Failed to convert byte array into valid ASN.1 string. String type as tag: {} Error: {}",
        tag,
        msg
    ))]
    StringConversionFailed {
        /// Universal tag of the string type.
        tag: Tag,
        /// The error's message.
        msg: alloc::string::String,
    },
    #[snafu(display(
    "Failed to convert byte array into valid fixed-sized ASN.1 string. String type as tag: {}, actual: {}, expected: {}",
    tag,
    actual,
    expected
    ))]
    FixedStringConversionFailed {
        /// Tag of the string type.
        tag: Tag,
        /// Expected length
        expected: usize,
        /// Actual length
        actual: usize,
    },
    #[snafu(display("No valid choice for `{}`", name))]
    NoValidChoice {
        /// The field's name.
        name: &'static str,
    },

    #[snafu(display("Attempted to decode extension on non-extensible type"))]
    TypeNotExtensible,
    /// Unexpected extra data found.
    #[snafu(display("Unexpected extra data found: length `{}` bytes", length))]
    UnexpectedExtraData {
        /// The amount of garbage data.
        length: usize,
    },
    #[snafu(display("Unknown field with index {} and tag {}", index, tag))]
    UnknownField { index: usize, tag: Tag },
    #[snafu(display("SEQUENCE has at least one required field, but no input provided"))]
    UnexpectedEmptyInput,
}

/// `DecodeError` kinds of `Kind::CodecSpecific` which are specific for BER.
#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
#[non_exhaustive]
pub enum BerDecodeErrorKind {
    #[snafu(display("Indefinite length encountered but not allowed."))]
    IndefiniteLengthNotAllowed,
    #[snafu(display("Invalid constructed identifier for ASN.1 value: not primitive."))]
    InvalidConstructedIdentifier,
    /// Invalid date.
    #[snafu(display("Invalid date string: {}", msg))]
    InvalidDate { msg: alloc::string::String },
    #[snafu(display("Invalid object identifier with missing or corrupt root nodes."))]
    InvalidObjectIdentifier,
    /// The tag does not match what was expected.
    #[snafu(display("Expected {:?} tag, actual tag: {:?}", expected, actual))]
    MismatchedTag {
        /// The expected tag.
        expected: Tag,
        /// The actual tag.
        actual: Tag,
    },
}

impl BerDecodeErrorKind {
    #[must_use]
    pub fn invalid_date(msg: alloc::string::String) -> CodecDecodeError {
        CodecDecodeError::Ber(Self::InvalidDate { msg })
    }
    pub fn assert_tag(expected: Tag, actual: Tag) -> core::result::Result<(), DecodeError> {
        if expected == actual {
            Ok(())
        } else {
            Err(BerDecodeErrorKind::MismatchedTag { expected, actual }.into())
        }
    }
}
// TODO check if there are more codec-specific errors here
/// `DecodeError` kinds of `Kind::CodecSpecific` which are specific for CER.
#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
#[non_exhaustive]
pub enum CerDecodeErrorKind {}

/// `DecodeError` kinds of `Kind::CodecSpecific` which are specific for DER.
#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
#[non_exhaustive]
pub enum DerDecodeErrorKind {
    #[snafu(display("Constructed encoding encountered but not allowed."))]
    ConstructedEncodingNotAllowed,
}

/// An error that occurred when decoding JER.
#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
#[non_exhaustive]
pub enum JerDecodeErrorKind {
    #[snafu(display("Unexpected end of input while decoding JER JSON."))]
    EndOfInput {},
    #[snafu(display(
        "Found mismatching JSON value. Expected type {}. Found value {}.",
        needed,
        found
    ))]
    TypeMismatch {
        needed: &'static str,
        found: alloc::string::String,
    },
    #[cfg(feature = "jer")]
    #[snafu(display("Found invalid byte in bit string. {parse_int_err}"))]
    InvalidJerBitstring { parse_int_err: ParseIntError },
    #[cfg(feature = "jer")]
    #[snafu(display("Found invalid character in octet string."))]
    InvalidJerOctetString {},
    #[cfg(feature = "jer")]
    #[snafu(display("Failed to construct OID from value {value}",))]
    InvalidOIDString { value: JsonValue },
    #[snafu(display("Found invalid enumerated discriminant {discriminant}",))]
    InvalidEnumDiscriminant { discriminant: alloc::string::String },
}

#[cfg(feature = "jer")]
impl JerDecodeErrorKind {
    pub fn eoi() -> CodecDecodeError {
        CodecDecodeError::Jer(JerDecodeErrorKind::EndOfInput {})
    }
}

// TODO check if there codec-specific errors here
/// `DecodeError` kinds of `Kind::CodecSpecific` which are specific for UPER.
#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
#[non_exhaustive]
pub enum UperDecodeErrorKind {}

// TODO check if there codec-specific errors here
/// `DecodeError` kinds of `Kind::CodecSpecific` which are specific for APER.
#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
#[non_exhaustive]
pub enum AperDecodeErrorKind {}

#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
#[non_exhaustive]
pub enum OerDecodeErrorKind {
    /// Tag class must be one of Universal (0b00), Application (0b01), Context (0b10) or Private (0b11).
    #[snafu(display("Invalid tag class when decoding choice: actual {:?}", class))]
    InvalidTagClassOnChoice {
        /// The actual class.
        class: u8,
    },
    #[snafu(display("Invalid tag number when decoding Choice. Value: {value}"))]
    InvalidTagNumberOnChoice { value: u32 },
    #[snafu(display(
        "Tag not found from the variants of the platform when decoding Choice. Tag: {value}, extensible status: {is_extensible}"
    ))]
    InvalidTagVariantOnChoice { value: Tag, is_extensible: bool },

    InvalidExtensionHeader {
        /// The amount of invalid bits.
        msg: alloc::string::String,
    },
    #[snafu(display("Invalid BitString: {msg}"))]
    InvalidOerBitString {
        /// The amount of invalid bits.
        msg: alloc::string::String,
    },
    #[snafu(display("Invalid preamble: {msg}"))]
    InvalidPreamble { msg: alloc::string::String },
}

impl OerDecodeErrorKind {
    #[must_use]
    pub fn invalid_tag_number_on_choice(value: u32) -> DecodeError {
        CodecDecodeError::Oer(Self::InvalidTagNumberOnChoice { value }).into()
    }
    #[must_use]
    pub fn invalid_tag_variant_on_choice(value: Tag, is_extensible: bool) -> DecodeError {
        CodecDecodeError::Oer(Self::InvalidTagVariantOnChoice {
            value,
            is_extensible,
        })
        .into()
    }

    #[must_use]
    pub fn invalid_extension_header(msg: alloc::string::String) -> DecodeError {
        CodecDecodeError::Oer(Self::InvalidExtensionHeader { msg }).into()
    }
    #[must_use]
    pub fn invalid_bit_string(msg: alloc::string::String) -> DecodeError {
        CodecDecodeError::Oer(Self::InvalidOerBitString { msg }).into()
    }
    #[must_use]
    pub fn invalid_preamble(msg: alloc::string::String) -> DecodeError {
        CodecDecodeError::Oer(Self::InvalidPreamble { msg }).into()
    }
}

#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
#[non_exhaustive]
pub enum CoerDecodeErrorKind {
    #[snafu(display("Invalid Canonical Octet Encoding, not encoded as the smallest possible number of octets: {msg}"))]
    NotValidCanonicalEncoding { msg: alloc::string::String },
}

impl crate::de::Error for DecodeError {
    fn custom<D: core::fmt::Display>(msg: D, codec: Codec) -> Self {
        Self::from_kind(
            DecodeErrorKind::Custom {
                msg: msg.to_string(),
            },
            codec,
        )
    }
    fn incomplete(needed: nom::Needed, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::Incomplete { needed }, codec)
    }

    fn exceeds_max_length(length: num_bigint::BigUint, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::ExceedsMaxLength { length }, codec)
    }

    fn missing_field(name: &'static str, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::MissingField { name }, codec)
    }

    fn no_valid_choice(name: &'static str, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::NoValidChoice { name }, codec)
    }

    fn field_error(name: &'static str, nested: DecodeError, codec: Codec) -> Self {
        Self::from_kind(
            DecodeErrorKind::FieldError {
                name,
                nested: Box::new(nested),
            },
            codec,
        )
    }

    fn duplicate_field(name: &'static str, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::DuplicateField { name }, codec)
    }
    fn unknown_field(index: usize, tag: Tag, codec: Codec) -> Self {
        Self::from_kind(DecodeErrorKind::UnknownField { index, tag }, codec)
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;
    #[test]
    fn test_ber_decode_date() {
        use crate::error::{DecodeError, DecodeErrorKind};
        // "230122130000-050Z" as bytes
        let data = [
            23, 17, 50, 51, 48, 49, 50, 50, 49, 51, 48, 48, 48, 48, 45, 48, 53, 48, 90,
        ];
        let result = crate::ber::decode::<UtcTime>(&data);
        match result {
            Err(DecodeError { kind, .. }) => {
                if let DecodeErrorKind::CodecSpecific {
                    inner:
                        crate::error::CodecDecodeError::Ber(
                            crate::error::BerDecodeErrorKind::InvalidDate { msg },
                        ),
                    ..
                } = *kind
                {
                    assert_eq!(msg, "230122130000-050Z");
                } else {
                    // Handle other kinds of errors
                    panic!("Unexpected error kind: {kind}");
                }
            }
            Ok(_) => panic!("Expected error"),
        }
    }
    #[test]
    fn test_uper_missing_choice_index() {
        use crate as rasn;
        use crate::error::{DecodeError, DecodeErrorKind};
        use crate::Codec;
        #[derive(AsnType, Decode, Debug, PartialEq)]
        #[rasn(choice, automatic_tags)]
        enum MyChoice {
            Normal(Integer),
            High(Integer),
            Medium(Integer),
        }
        // Value 333 encoded for missing choice index 3
        let data = [192, 128, 83, 64];
        let result = Codec::Uper.decode_from_binary::<MyChoice>(&data);
        match result {
            Ok(_) => {
                panic!("Unexpected OK!");
            }
            Err(DecodeError { kind, .. }) => {
                if let DecodeErrorKind::ChoiceIndexNotFound { index, .. } = *kind {
                    assert_eq!(index, 3);
                } else {
                    // Handle other kinds of errors
                    panic!("Unexpected error kind: {kind}");
                }
            }
        }
    }
}