asn1/
parser.rs

1use crate::types::{Asn1Readable, SimpleAsn1Readable, Tlv};
2use crate::Tag;
3use core::fmt;
4
5#[derive(Debug, PartialEq, Eq, Clone, Copy)]
6pub enum ParseErrorKind {
7    /// Something about the value was invalid.
8    InvalidValue,
9    /// Something about the tag was invalid. This refers to a syntax error,
10    /// not a tag's value being unexpected.
11    InvalidTag,
12    /// Something about the length was invalid. This can mean either a invalid
13    /// encoding, or that a TLV was longer than 4GB, which is the maximum
14    /// length that rust-asn1 supports.
15    InvalidLength,
16    /// A container's size was invalid. This typically indicates an empty
17    /// or oversized structure.
18    InvalidSize {
19        min: usize,
20        max: usize,
21        actual: usize,
22    },
23    /// An unexpected tag was encountered.
24    UnexpectedTag { actual: Tag },
25    /// There was not enough data available to complete parsing. `needed`
26    /// indicates the amount of data required to advance the parse.
27    ///
28    /// Note that providing `needed` additional bytes of data does not ensure
29    /// that `parse` will succeed -- it is the amount of data required to
30    /// satisfy the `read` operation that failed, and there may be subsequent
31    /// `read` operations that require additional data.
32    ShortData { needed: usize },
33    /// An internal computation would have overflowed.
34    IntegerOverflow,
35    /// There was extraneous data in the input.
36    ExtraData,
37    /// Elements of a set were not lexicographically sorted.
38    InvalidSetOrdering,
39    /// An OPTIONAL DEFAULT was written with a default value.
40    EncodedDefault,
41    /// OID value is longer than the maximum size rust-asn1 can store. This is
42    /// a limitation of rust-asn1.
43    OidTooLong,
44    /// A `DEFINED BY` value received an value for which there was no known
45    /// variant.
46    UnknownDefinedBy,
47}
48
49#[derive(Debug, PartialEq, Eq)]
50#[doc(hidden)]
51pub enum ParseLocation {
52    Field(&'static str),
53    Index(usize),
54}
55
56/// `ParseError` are returned when there is an error parsing the ASN.1 data.
57#[derive(PartialEq, Eq)]
58pub struct ParseError {
59    kind: ParseErrorKind,
60    parse_locations: [Option<ParseLocation>; 4],
61    parse_depth: u8,
62}
63
64impl ParseError {
65    pub const fn new(kind: ParseErrorKind) -> ParseError {
66        ParseError {
67            kind,
68            parse_locations: [None, None, None, None],
69            parse_depth: 0,
70        }
71    }
72
73    pub fn kind(&self) -> ParseErrorKind {
74        self.kind
75    }
76
77    #[doc(hidden)]
78    #[must_use]
79    pub fn add_location(mut self, loc: ParseLocation) -> Self {
80        if (self.parse_depth as usize) < self.parse_locations.len() {
81            self.parse_locations[self.parse_depth as usize] = Some(loc);
82            self.parse_depth += 1;
83        }
84        self
85    }
86}
87
88#[cfg(feature = "std")]
89impl std::error::Error for ParseError {}
90
91// Wraps an `Option<T>`, but `fmt::Debug` will only render `Some` values and
92// panics on others.
93struct SomeFmtOption<T>(Option<T>);
94
95impl<T: fmt::Debug> fmt::Debug for SomeFmtOption<T> {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        self.0.as_ref().unwrap().fmt(f)
98    }
99}
100
101impl fmt::Debug for ParseError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        let mut f = f.debug_struct("ParseError");
104        f.field("kind", &self.kind);
105        if self.parse_depth > 0 {
106            let mut locations = [
107                SomeFmtOption(None),
108                SomeFmtOption(None),
109                SomeFmtOption(None),
110                SomeFmtOption(None),
111                SomeFmtOption(None),
112                SomeFmtOption(None),
113                SomeFmtOption(None),
114                SomeFmtOption(None),
115            ];
116            for (i, location) in self.parse_locations[..self.parse_depth as usize]
117                .iter()
118                .rev()
119                .enumerate()
120            {
121                locations[i] = match location.as_ref().unwrap() {
122                    ParseLocation::Field(f) => SomeFmtOption(Some(f as &dyn fmt::Debug)),
123                    ParseLocation::Index(i) => SomeFmtOption(Some(i as &dyn fmt::Debug)),
124                }
125            }
126
127            f.field("location", &&locations[..self.parse_depth as usize]);
128        }
129        f.finish()
130    }
131}
132
133impl fmt::Display for ParseError {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        write!(f, "ASN.1 parsing error: ")?;
136        match self.kind {
137            ParseErrorKind::InvalidValue => write!(f, "invalid value"),
138            ParseErrorKind::InvalidTag => write!(f, "invalid tag"),
139            ParseErrorKind::InvalidLength => write!(f, "invalid length"),
140            ParseErrorKind::InvalidSize { min, max, actual } => {
141                write!(
142                    f,
143                    "invalid container size (expected between {min} and {max}, got {actual})"
144                )
145            }
146            ParseErrorKind::UnexpectedTag { actual } => {
147                write!(f, "unexpected tag (got {actual:?})")
148            }
149            ParseErrorKind::ShortData { needed } => {
150                write!(f, "short data (needed at least {needed} additional bytes)")
151            }
152            ParseErrorKind::IntegerOverflow => write!(f, "integer overflow"),
153            ParseErrorKind::ExtraData => write!(f, "extra data"),
154            ParseErrorKind::InvalidSetOrdering => write!(f, "SET value was ordered incorrectly"),
155            ParseErrorKind::EncodedDefault => write!(f, "DEFAULT value was explicitly encoded"),
156            ParseErrorKind::OidTooLong => write!(
157                f,
158                "OBJECT IDENTIFIER was too large to be stored in rust-asn1's buffer"
159            ),
160            ParseErrorKind::UnknownDefinedBy => write!(f, "DEFINED BY with unknown value"),
161        }
162    }
163}
164
165/// The result of a `parse`. Either a successful value or a `ParseError`.
166pub type ParseResult<T> = Result<T, ParseError>;
167
168/// Parse takes a sequence of bytes of DER encoded ASN.1 data, constructs a
169/// parser, and invokes a callback to read elements from the ASN.1 parser.
170pub fn parse<'a, T, E: From<ParseError>, F: FnOnce(&mut Parser<'a>) -> Result<T, E>>(
171    data: &'a [u8],
172    f: F,
173) -> Result<T, E> {
174    let mut p = Parser::new(data);
175    let result = f(&mut p)?;
176    p.finish()?;
177    Ok(result)
178}
179
180/// Parses a single top-level ASN.1 element from `data` (does not allow
181/// trailing data). Most often this will be used where `T` is a type with
182/// `#[derive(asn1::Asn1Read)]`.
183pub fn parse_single<'a, T: Asn1Readable<'a>>(data: &'a [u8]) -> ParseResult<T> {
184    parse(data, Parser::read_element::<T>)
185}
186
187/// Attempts to parse the `Tlv` at the start of `data` (allows trailing data).
188/// If successful, the `Tlv` and the trailing data after it are returned, if
189/// unsuccessful a `ParseError` is returned.
190///
191/// This can be useful where you have a file or stream format that relies on
192/// ASN.1 TLVs for framing.
193///
194/// When parsing a stream, if an error is returned, if its `kind` is
195/// `ParseErrorKind::ShortData`, this indicates that `data` did not contain
196/// sufficient data to parse an entire `Tlv`, and thus adding more data may
197/// resolve this. All other errors are "fatal" and cannot be resolved with
198/// additional data.
199pub fn strip_tlv(data: &[u8]) -> ParseResult<(Tlv<'_>, &[u8])> {
200    let mut p = Parser::new(data);
201    let tlv = p.read_element::<Tlv<'_>>()?;
202    Ok((tlv, p.data))
203}
204
205/// Encapsulates an ongoing parse. For almost all use-cases the correct
206/// entry-point is [`parse`] or [`parse_single`].
207pub struct Parser<'a> {
208    data: &'a [u8],
209}
210
211impl<'a> Parser<'a> {
212    #[inline]
213    pub(crate) fn new(data: &'a [u8]) -> Parser<'a> {
214        Parser { data }
215    }
216
217    #[inline]
218    fn finish(self) -> ParseResult<()> {
219        if !self.is_empty() {
220            return Err(ParseError::new(ParseErrorKind::ExtraData));
221        }
222        Ok(())
223    }
224
225    pub(crate) fn clone_internal(&self) -> Parser<'a> {
226        Parser::new(self.data)
227    }
228
229    /// Returns the tag of the next element, without consuming it.
230    pub fn peek_tag(&mut self) -> Option<Tag> {
231        let (tag, _) = Tag::from_bytes(self.data).ok()?;
232        Some(tag)
233    }
234
235    pub(crate) fn read_tag(&mut self) -> ParseResult<Tag> {
236        let (tag, data) = Tag::from_bytes(self.data)?;
237        self.data = data;
238        Ok(tag)
239    }
240
241    #[inline]
242    fn read_u8(&mut self) -> ParseResult<u8> {
243        Ok(self.read_bytes(1)?[0])
244    }
245
246    #[inline]
247    fn read_bytes(&mut self, length: usize) -> ParseResult<&'a [u8]> {
248        if length > self.data.len() {
249            return Err(ParseError::new(ParseErrorKind::ShortData {
250                needed: length - self.data.len(),
251            }));
252        }
253        let (result, data) = self.data.split_at(length);
254        self.data = data;
255        Ok(result)
256    }
257
258    fn read_length(&mut self) -> ParseResult<usize> {
259        match self.read_u8()? {
260            n if (n & 0x80) == 0 => Ok(usize::from(n)),
261            0x81 => {
262                let length = usize::from(self.read_u8()?);
263                // Do not allow values <0x80 to be encoded using the long form
264                if length < 0x80 {
265                    return Err(ParseError::new(ParseErrorKind::InvalidLength));
266                }
267                Ok(length)
268            }
269            0x82 => {
270                let length_bytes = self.read_bytes(2)?;
271                let length = (usize::from(length_bytes[0]) << 8) | usize::from(length_bytes[1]);
272                // Enforce that we're not using long form for values <0x80,
273                // and that the first byte of the length is not zero (i.e.
274                // that we're minimally encoded)
275                if length < 0x100 {
276                    return Err(ParseError::new(ParseErrorKind::InvalidLength));
277                }
278                Ok(length)
279            }
280            0x83 => {
281                let length_bytes = self.read_bytes(3)?;
282                let length = (usize::from(length_bytes[0]) << 16)
283                    | (usize::from(length_bytes[1]) << 8)
284                    | usize::from(length_bytes[2]);
285                // Same thing as the 0x82 case
286                if length < 0x10000 {
287                    return Err(ParseError::new(ParseErrorKind::InvalidLength));
288                }
289                Ok(length)
290            }
291            0x84 => {
292                let length_bytes = self.read_bytes(4)?;
293                let length = (usize::from(length_bytes[0]) << 24)
294                    | (usize::from(length_bytes[1]) << 16)
295                    | (usize::from(length_bytes[2]) << 8)
296                    | usize::from(length_bytes[3]);
297                // Same thing as the 0x82 case
298                if length < 0x1000000 {
299                    return Err(ParseError::new(ParseErrorKind::InvalidLength));
300                }
301                Ok(length)
302            }
303            // We only support four-byte lengths
304            _ => Err(ParseError::new(ParseErrorKind::InvalidLength)),
305        }
306    }
307
308    #[inline]
309    pub(crate) fn read_tlv(&mut self) -> ParseResult<Tlv<'a>> {
310        let initial_data = self.data;
311
312        let tag = self.read_tag()?;
313        let length = self.read_length()?;
314        let data = self.read_bytes(length)?;
315
316        let full_data = &initial_data[..initial_data.len() - self.data.len()];
317        Ok(Tlv {
318            tag,
319            data,
320            full_data,
321        })
322    }
323
324    /// Tests whether there is any data remaining in the Parser. Generally
325    /// useful when parsing a `SEQUENCE OF`.
326    #[inline]
327    pub fn is_empty(&self) -> bool {
328        self.data.is_empty()
329    }
330
331    /// Reads a single ASN.1 element from the parser. Which type you are reading is determined by
332    /// the type parameter `T`.
333    #[inline]
334    pub fn read_element<T: Asn1Readable<'a>>(&mut self) -> ParseResult<T> {
335        T::parse(self)
336    }
337
338    /// This is an alias for `read_element::<Explicit<T, tag>>` for use when
339    /// the tag is not known at compile time.
340    pub fn read_explicit_element<T: Asn1Readable<'a>>(&mut self, tag: u32) -> ParseResult<T> {
341        let expected_tag = crate::explicit_tag(tag);
342        let tlv = self.read_tlv()?;
343        if tlv.tag != expected_tag {
344            return Err(ParseError::new(ParseErrorKind::UnexpectedTag {
345                actual: tlv.tag,
346            }));
347        }
348        parse_single(tlv.data())
349    }
350
351    /// This is an alias for `read_element::<Implicit<T, tag>>` for use when
352    /// the tag is not known at compile time.
353    pub fn read_implicit_element<T: SimpleAsn1Readable<'a>>(&mut self, tag: u32) -> ParseResult<T> {
354        let expected_tag = crate::implicit_tag(tag, T::TAG);
355        let tlv = self.read_tlv()?;
356        if tlv.tag != expected_tag {
357            return Err(ParseError::new(ParseErrorKind::UnexpectedTag {
358                actual: tlv.tag,
359            }));
360        }
361        T::parse_data(tlv.data())
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::Parser;
368    use crate::tag::TagClass;
369    use crate::types::Asn1Readable;
370    use crate::{
371        BMPString, BigInt, BigUint, BitString, Choice1, Choice2, Choice3, DateTime, Enumerated,
372        Explicit, GeneralizedTime, IA5String, Implicit, ObjectIdentifier, OctetStringEncoded,
373        OwnedBigInt, OwnedBigUint, OwnedBitString, ParseError, ParseErrorKind, ParseLocation,
374        ParseResult, PrintableString, Sequence, SequenceOf, SetOf, Tag, Tlv, UniversalString,
375        UtcTime, Utf8String, VisibleString, X509GeneralizedTime,
376    };
377    #[cfg(not(feature = "std"))]
378    use alloc::boxed::Box;
379    use alloc::{format, vec};
380    use core::fmt;
381
382    #[test]
383    fn test_lifetimes() {
384        // Explicit 'static OCTET_STRING
385        let result = crate::parse(b"\x04\x01\x00", |p| p.read_element::<&'static [u8]>()).unwrap();
386        assert_eq!(result, b"\x00");
387
388        // Explicit 'static SEQUENCE containing an explicit 'static OCTET_STRING
389        let result = crate::parse(b"\x30\x03\x04\x01\x00", |p| {
390            p.read_element::<Sequence<'static>>()?
391                .parse(|p| p.read_element::<&'static [u8]>())
392        })
393        .unwrap();
394        assert_eq!(result, b"\x00");
395
396        // Automatic 'static OCTET_STRING
397        let result = crate::parse(b"\x04\x01\x00", |p| p.read_element::<&[u8]>()).unwrap();
398        assert_eq!(result, b"\x00");
399
400        // Automatic 'static SEQUENCE containing an automatic 'static
401        // OCTET_STRING
402        let result = crate::parse(b"\x30\x03\x04\x01\x00", |p| {
403            p.read_element::<Sequence<'_>>()?
404                .parse(|p| p.read_element::<&[u8]>())
405        })
406        .unwrap();
407        assert_eq!(result, b"\x00");
408
409        // BIT_STRING
410        let result = crate::parse::<_, ParseError, _>(b"\x03\x02\x00\x00", |p| {
411            Ok(p.read_element::<BitString<'_>>()?.as_bytes())
412        })
413        .unwrap();
414        assert_eq!(result, b"\x00");
415    }
416
417    #[test]
418    fn test_parse_error_debug() {
419        for (e, expected) in &[
420            (
421                ParseError::new(ParseErrorKind::InvalidValue),
422                "ParseError { kind: InvalidValue }",
423            ),
424            (
425                ParseError::new(ParseErrorKind::InvalidValue)
426                    .add_location(ParseLocation::Field("Abc::123")),
427                "ParseError { kind: InvalidValue, location: [\"Abc::123\"] }",
428            ),
429            (
430                ParseError::new(ParseErrorKind::InvalidValue)
431                    .add_location(ParseLocation::Index(12))
432                    .add_location(ParseLocation::Field("Abc::123")),
433                "ParseError { kind: InvalidValue, location: [\"Abc::123\", 12] }",
434            ),
435        ] {
436            assert_eq!(&format!("{e:?}"), expected);
437        }
438    }
439
440    #[test]
441    fn test_parse_error_display() {
442        for (e, expected) in &[
443            (
444                ParseError::new(ParseErrorKind::InvalidValue),
445                "ASN.1 parsing error: invalid value",
446            ),
447            (
448                ParseError::new(ParseErrorKind::InvalidTag),
449                "ASN.1 parsing error: invalid tag"
450            ),
451            (
452                ParseError::new(ParseErrorKind::InvalidLength),
453                "ASN.1 parsing error: invalid length"
454            ),
455            (
456                ParseError::new(ParseErrorKind::InvalidSize { min: 1, max: 5, actual: 0 }),
457                "ASN.1 parsing error: invalid container size (expected between 1 and 5, got 0)",
458            ),
459            (
460                ParseError::new(ParseErrorKind::IntegerOverflow),
461                "ASN.1 parsing error: integer overflow"
462            ),
463            (
464                ParseError::new(ParseErrorKind::ExtraData),
465                "ASN.1 parsing error: extra data"
466            ),
467            (
468                ParseError::new(ParseErrorKind::InvalidSetOrdering),
469                "ASN.1 parsing error: SET value was ordered incorrectly"
470            ),
471            (
472                ParseError::new(ParseErrorKind::EncodedDefault),
473                "ASN.1 parsing error: DEFAULT value was explicitly encoded"
474            ),
475            (
476                ParseError::new(ParseErrorKind::OidTooLong),
477                "ASN.1 parsing error: OBJECT IDENTIFIER was too large to be stored in rust-asn1's buffer"
478            ),
479            (
480                ParseError::new(ParseErrorKind::UnknownDefinedBy),
481                "ASN.1 parsing error: DEFINED BY with unknown value"
482            ),
483            (
484                ParseError::new(ParseErrorKind::ShortData{needed: 7})
485                    .add_location(ParseLocation::Field("Abc::123")),
486                "ASN.1 parsing error: short data (needed at least 7 additional bytes)",
487            ),
488            (
489                ParseError::new(ParseErrorKind::UnexpectedTag {
490                    actual: Tag::primitive(12),
491                })
492                .add_location(ParseLocation::Index(12))
493                .add_location(ParseLocation::Field("Abc::123")),
494                "ASN.1 parsing error: unexpected tag (got Tag { value: 12, constructed: false, class: Universal })",
495            ),
496        ]
497        {
498            assert_eq!(&format!("{e}"), expected);
499        }
500    }
501
502    #[test]
503    fn test_parse_error_kind() {
504        let e = ParseError::new(ParseErrorKind::EncodedDefault);
505        assert_eq!(e.kind(), ParseErrorKind::EncodedDefault);
506    }
507
508    #[test]
509    fn test_strip_tlv() {
510        for (der_bytes, expected) in [
511            (
512                b"" as &[u8],
513                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
514            ),
515            (
516                b"\x04",
517                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
518            ),
519            (
520                b"\x04\x82",
521                Err(ParseError::new(ParseErrorKind::ShortData { needed: 2 })),
522            ),
523            (
524                b"\x04\x03",
525                Err(ParseError::new(ParseErrorKind::ShortData { needed: 3 })),
526            ),
527            (
528                b"\x04\x03ab",
529                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
530            ),
531            (
532                b"\x04\x03abc",
533                Ok((
534                    Tlv {
535                        tag: Tag::primitive(0x04),
536                        data: b"abc",
537                        full_data: b"\x04\x03abc",
538                    },
539                    b"" as &[u8],
540                )),
541            ),
542            (
543                b"\x04\x03abc\x00\x00\x00",
544                Ok((
545                    Tlv {
546                        tag: Tag::primitive(0x04),
547                        data: b"abc",
548                        full_data: b"\x04\x03abc",
549                    },
550                    b"\x00\x00\x00",
551                )),
552            ),
553        ] {
554            let result = crate::strip_tlv(der_bytes);
555            assert_eq!(result, expected);
556        }
557    }
558
559    fn assert_parses_cb<
560        'a,
561        T: fmt::Debug + PartialEq,
562        E: From<ParseError> + fmt::Debug + PartialEq,
563        F: Fn(&mut Parser<'a>) -> Result<T, E>,
564    >(
565        data: &[(Result<T, E>, &'a [u8])],
566        f: F,
567    ) {
568        for (expected, der_bytes) in data {
569            let result = crate::parse(der_bytes, &f);
570            assert_eq!(&result, expected);
571        }
572    }
573
574    fn assert_parses<'a, T>(data: &[(ParseResult<T>, &'a [u8])])
575    where
576        T: Asn1Readable<'a> + fmt::Debug + PartialEq,
577    {
578        assert_parses_cb(data, |p| p.read_element::<T>());
579    }
580
581    #[test]
582    fn test_parse_extra_data() {
583        let result = crate::parse(b"\x00", |_| Ok(()));
584        assert_eq!(result, Err(ParseError::new(ParseErrorKind::ExtraData)));
585    }
586
587    #[test]
588    fn test_peek_tag() {
589        let result = crate::parse(b"\x02\x01\x7f", |p| {
590            assert_eq!(p.peek_tag(), Some(Tag::primitive(0x02)));
591            p.read_element::<u8>()
592        });
593        assert_eq!(result, Ok(127));
594    }
595
596    #[test]
597    fn test_errors() {
598        #[derive(Debug, PartialEq, Eq)]
599        enum E {
600            X(u64),
601            P(ParseError),
602        }
603
604        impl From<ParseError> for E {
605            fn from(e: ParseError) -> E {
606                E::P(e)
607            }
608        }
609
610        assert_parses_cb(
611            &[
612                (Ok(8), b"\x02\x01\x08"),
613                (
614                    Err(E::P(ParseError::new(ParseErrorKind::ShortData {
615                        needed: 1,
616                    }))),
617                    b"\x02\x01",
618                ),
619                (Err(E::X(7)), b"\x02\x01\x07"),
620            ],
621            |p| {
622                let val = p.read_element::<u64>()?;
623                if val % 2 == 0 {
624                    Ok(val)
625                } else {
626                    Err(E::X(val))
627                }
628            },
629        );
630    }
631
632    #[test]
633    fn test_parse_tlv() {
634        assert_parses::<Tlv<'_>>(&[
635            (
636                Ok(Tlv {
637                    tag: Tag::primitive(0x4),
638                    data: b"abc",
639                    full_data: b"\x04\x03abc",
640                }),
641                b"\x04\x03abc",
642            ),
643            (
644                Err(ParseError::new(ParseErrorKind::ShortData { needed: 2 })),
645                b"\x04\x03a",
646            ),
647            (
648                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
649                b"\x04",
650            ),
651            (
652                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
653                b"",
654            ),
655            // Long form tags
656            (
657                Ok(Tlv {
658                    tag: Tag::new(31, TagClass::Universal, false),
659                    data: b"",
660                    full_data: b"\x1f\x1f\x00",
661                }),
662                b"\x1f\x1f\x00",
663            ),
664            (
665                Ok(Tlv {
666                    tag: Tag::new(128, TagClass::Universal, false),
667                    data: b"",
668                    full_data: b"\x1f\x81\x00\x00",
669                }),
670                b"\x1f\x81\x00\x00",
671            ),
672            (
673                Ok(Tlv {
674                    tag: Tag::new(0x4001, TagClass::Universal, false),
675                    data: b"",
676                    full_data: b"\x1f\x81\x80\x01\x00",
677                }),
678                b"\x1f\x81\x80\x01\x00",
679            ),
680            (
681                Ok(Tlv {
682                    tag: Tag::new(0x01, TagClass::Application, false),
683                    data: b"",
684                    full_data: b"\x41\x00",
685                }),
686                b"\x41\x00",
687            ),
688            (
689                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
690                b"\x1f",
691            ),
692            (
693                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
694                b"\xff",
695            ),
696            (
697                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
698                b"\x1f\x85",
699            ),
700            // Overflow u32 for the tag number.
701            (
702                Err(ParseError::new(ParseErrorKind::InvalidTag)),
703                b"\x1f\x88\x80\x80\x80\x80\x00",
704            ),
705            // Long form tag for value that fits in a short form
706            (
707                Err(ParseError::new(ParseErrorKind::InvalidTag)),
708                b"\x1f\x1e\x00",
709            ),
710            (
711                // base128 integer with leading 0
712                Err(ParseError::new(ParseErrorKind::InvalidTag)),
713                b"\xff\x80\x84\x01\x01\xa9",
714            ),
715        ]);
716    }
717
718    #[test]
719    fn test_parse_null() {
720        assert_parses::<()>(&[
721            (Ok(()), b"\x05\x00"),
722            (
723                Err(ParseError::new(ParseErrorKind::InvalidValue)),
724                b"\x05\x01\x00",
725            ),
726        ]);
727    }
728
729    #[test]
730    fn test_parse_bool() {
731        assert_parses::<bool>(&[
732            (Ok(true), b"\x01\x01\xff"),
733            (Ok(false), b"\x01\x01\x00"),
734            (
735                Err(ParseError::new(ParseErrorKind::InvalidValue)),
736                b"\x01\x00",
737            ),
738            (
739                Err(ParseError::new(ParseErrorKind::InvalidValue)),
740                b"\x01\x01\x01",
741            ),
742            (
743                Err(ParseError::new(ParseErrorKind::InvalidValue)),
744                b"\x01\x02\x00\x00",
745            ),
746            (
747                Err(ParseError::new(ParseErrorKind::InvalidValue)),
748                b"\x01\x02\xff\x01",
749            ),
750        ]);
751    }
752
753    #[test]
754    fn test_parse_octet_string() {
755        let long_value = vec![b'a'; 70_000];
756        let really_long_value = vec![b'a'; 20_000_000];
757
758        assert_parses::<&[u8]>(&[
759            (Ok(b""), b"\x04\x00"),
760            (Ok(b"\x01\x02\x03"), b"\x04\x03\x01\x02\x03"),
761            (
762                Ok(b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
763                b"\x04\x81\x81aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
764            ),
765            (
766                Ok(long_value.as_slice()),
767                [b"\x04\x83\x01\x11\x70", long_value.as_slice()].concat().as_slice()
768            ),
769            (
770                Ok(really_long_value.as_slice()),
771                [b"\x04\x84\x01\x31\x2d\x00", really_long_value.as_slice()].concat().as_slice()
772            ),
773            (Err(ParseError::new(ParseErrorKind::InvalidLength)), b"\x04\x80"),
774            (Err(ParseError::new(ParseErrorKind::InvalidLength)), b"\x04\x81\x00"),
775            (Err(ParseError::new(ParseErrorKind::InvalidLength)), b"\x04\x81\x01\x09"),
776            (Err(ParseError::new(ParseErrorKind::InvalidLength)), b"\x04\x82\x00\x80"),
777            (
778                Err(ParseError::new(ParseErrorKind::InvalidLength)),
779                b"\x04\x89\x01\x01\x01\x01\x01\x01\x01\x01\x01"
780            ),
781            (Err(ParseError::new(ParseErrorKind::ShortData{needed: 1})), b"\x04\x03\x01\x02"),
782            (Err(ParseError::new(ParseErrorKind::ShortData{needed: 65531})), b"\x04\x82\xff\xff\xff\xff\xff\xff"),
783            // 3 byte length form with leading 0.
784            (Err(ParseError::new(ParseErrorKind::InvalidLength)), b"\x04\x83\x00\xff\xff"),
785            // 4 byte length form with leading 0.
786            (Err(ParseError::new(ParseErrorKind::InvalidLength)), b"\x04\x84\x00\xff\xff\xff"),
787        ]);
788
789        assert_parses::<[u8; 0]>(&[
790            (Ok([]), b"\x04\x00"),
791            (
792                Err(ParseError::new(ParseErrorKind::InvalidValue)),
793                b"\x04\x02\x01\x02",
794            ),
795        ]);
796
797        assert_parses::<[u8; 1]>(&[
798            (Ok([2]), b"\x04\x01\x02"),
799            (
800                Err(ParseError::new(ParseErrorKind::InvalidValue)),
801                b"\x04\x00",
802            ),
803            (
804                Err(ParseError::new(ParseErrorKind::InvalidValue)),
805                b"\x04\x02\x01\x02",
806            ),
807        ]);
808    }
809
810    #[test]
811    fn test_octet_string_encoded() {
812        assert_parses::<OctetStringEncoded<bool>>(&[
813            (Ok(OctetStringEncoded::new(true)), b"\x04\x03\x01\x01\xff"),
814            (Ok(OctetStringEncoded::new(false)), b"\x04\x03\x01\x01\x00"),
815            (
816                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
817                    actual: Tag::primitive(0x03),
818                })),
819                b"\x03\x00",
820            ),
821            (
822                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
823                    actual: Tag::primitive(0x02),
824                })),
825                b"\x04\x02\x02\x00",
826            ),
827        ])
828    }
829
830    #[test]
831    fn test_parse_int_i64() {
832        assert_parses::<i64>(&[
833            (Ok(0), b"\x02\x01\x00"),
834            (Ok(127), b"\x02\x01\x7f"),
835            (Ok(128), b"\x02\x02\x00\x80"),
836            (Ok(256), b"\x02\x02\x01\x00"),
837            (Ok(-128), b"\x02\x01\x80"),
838            (Ok(-129), b"\x02\x02\xff\x7f"),
839            (Ok(-256), b"\x02\x02\xff\x00"),
840            (Ok(i64::MAX), b"\x02\x08\x7f\xff\xff\xff\xff\xff\xff\xff"),
841            (
842                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
843                    actual: Tag::primitive(0x3),
844                })),
845                b"\x03\x00",
846            ),
847            (
848                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
849                b"\x02\x02\x00",
850            ),
851            (
852                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
853                b"",
854            ),
855            (
856                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
857                b"\x02",
858            ),
859            (
860                Err(ParseError::new(ParseErrorKind::IntegerOverflow)),
861                b"\x02\x09\x02\x00\x00\x00\x00\x00\x00\x00\x00",
862            ),
863            (
864                Err(ParseError::new(ParseErrorKind::InvalidValue)),
865                b"\x02\x05\x00\x00\x00\x00\x01",
866            ),
867            (
868                Err(ParseError::new(ParseErrorKind::InvalidValue)),
869                b"\x02\x02\xff\x80",
870            ),
871            (
872                Err(ParseError::new(ParseErrorKind::InvalidValue)),
873                b"\x02\x00",
874            ),
875            (
876                Err(ParseError::new(ParseErrorKind::IntegerOverflow)),
877                b"\x02\x09\x00\xD0\x07\x04\x00\x03\x31\x31\x00",
878            ),
879        ]);
880    }
881
882    #[test]
883    fn parse_int_u64() {
884        assert_parses::<u64>(&[
885            (
886                Ok(u64::MAX),
887                b"\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff",
888            ),
889            (
890                Err(ParseError::new(ParseErrorKind::InvalidValue)),
891                b"\x02\x01\xff",
892            ),
893            (
894                Err(ParseError::new(ParseErrorKind::IntegerOverflow)),
895                b"\x02\x09\x02\x00\x00\x00\x00\x00\x00\x00\x00",
896            ),
897        ]);
898    }
899
900    #[test]
901    fn test_parse_int_i32() {
902        assert_parses::<i32>(&[
903            (Ok(0), b"\x02\x01\x00"),
904            (Ok(127), b"\x02\x01\x7f"),
905            (Ok(128), b"\x02\x02\x00\x80"),
906            (Ok(256), b"\x02\x02\x01\x00"),
907            (Ok(-128), b"\x02\x01\x80"),
908            (Ok(-129), b"\x02\x02\xff\x7f"),
909            (Ok(-256), b"\x02\x02\xff\x00"),
910            (Ok(i32::MAX), b"\x02\x04\x7f\xff\xff\xff"),
911            (
912                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
913                    actual: Tag::primitive(0x3),
914                })),
915                b"\x03\x00",
916            ),
917            (
918                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
919                b"\x02\x02\x00",
920            ),
921            (
922                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
923                b"",
924            ),
925            (
926                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
927                b"\x02",
928            ),
929            (
930                Err(ParseError::new(ParseErrorKind::IntegerOverflow)),
931                b"\x02\x09\x02\x00\x00\x00\x00\x00\x00\x00\x00",
932            ),
933            (
934                Err(ParseError::new(ParseErrorKind::InvalidValue)),
935                b"\x02\x05\x00\x00\x00\x00\x01",
936            ),
937            (
938                Err(ParseError::new(ParseErrorKind::InvalidValue)),
939                b"\x02\x02\xff\x80",
940            ),
941            (
942                Err(ParseError::new(ParseErrorKind::InvalidValue)),
943                b"\x02\x00",
944            ),
945        ]);
946    }
947
948    #[test]
949    fn test_parse_int_u16() {
950        assert_parses::<u16>(&[
951            (Ok(0), b"\x02\x01\x00"),
952            (Ok(1), b"\x02\x01\x01"),
953            (Ok(256), b"\x02\x02\x01\x00"),
954            (Ok(65535), b"\x02\x03\x00\xff\xff"),
955            (
956                Err(ParseError::new(ParseErrorKind::IntegerOverflow)),
957                b"\x02\x03\x01\x00\x00",
958            ),
959        ]);
960    }
961
962    #[test]
963    fn test_parse_int_i16() {
964        assert_parses::<i16>(&[
965            (Ok(0), b"\x02\x01\x00"),
966            (Ok(1), b"\x02\x01\x01"),
967            (Ok(-256), b"\x02\x02\xff\x00"),
968            (Ok(-1), b"\x02\x01\xff"),
969            (Ok(-32768), b"\x02\x02\x80\x00"),
970            (Ok(32767), b"\x02\x02\x7f\xff"),
971            (
972                Err(ParseError::new(ParseErrorKind::IntegerOverflow)),
973                b"\x02\x03\x80\x00\x00",
974            ),
975        ]);
976    }
977
978    #[test]
979    fn test_parse_int_i8() {
980        assert_parses::<i8>(&[
981            (Ok(0i8), b"\x02\x01\x00"),
982            (Ok(127i8), b"\x02\x01\x7f"),
983            (Ok(-128i8), b"\x02\x01\x80"),
984            (
985                Err(ParseError::new(ParseErrorKind::IntegerOverflow)),
986                b"\x02\x02\x02\x00",
987            ),
988            (
989                Err(ParseError::new(ParseErrorKind::InvalidValue)),
990                b"\x02\x00",
991            ),
992        ]);
993    }
994
995    #[test]
996    fn test_parse_int_u8() {
997        assert_parses::<u8>(&[
998            (Ok(0u8), b"\x02\x01\x00"),
999            (Ok(127u8), b"\x02\x01\x7f"),
1000            (Ok(255u8), b"\x02\x02\x00\xff"),
1001            (
1002                Err(ParseError::new(ParseErrorKind::IntegerOverflow)),
1003                b"\x02\x02\x01\x00",
1004            ),
1005            (
1006                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1007                b"\x02\x01\x80",
1008            ),
1009        ]);
1010    }
1011
1012    #[test]
1013    fn test_parse_biguint() {
1014        assert_parses::<BigUint<'_>>(&[
1015            (Ok(BigUint::new(b"\x00").unwrap()), b"\x02\x01\x00"),
1016            (Ok(BigUint::new(b"\x00\xff").unwrap()), b"\x02\x02\x00\xff"),
1017            (
1018                Ok(BigUint::new(b"\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff").unwrap()),
1019                b"\x02\x0d\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
1020            ),
1021            (
1022                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1023                b"\x02\x00",
1024            ),
1025            (
1026                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1027                b"\x02\x01\x80",
1028            ),
1029            (
1030                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1031                b"\x02\x02\xff\x80",
1032            ),
1033        ]);
1034    }
1035
1036    #[test]
1037    fn test_parse_ownedbiguint() {
1038        assert_parses::<OwnedBigUint>(&[
1039            (
1040                Ok(OwnedBigUint::new(b"\x00".to_vec()).unwrap()),
1041                b"\x02\x01\x00",
1042            ),
1043            (
1044                Ok(OwnedBigUint::new(b"\x00\xff".to_vec()).unwrap()),
1045                b"\x02\x02\x00\xff",
1046            ),
1047            (
1048                Ok(OwnedBigUint::new(
1049                    b"\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff".to_vec(),
1050                )
1051                .unwrap()),
1052                b"\x02\x0d\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
1053            ),
1054            (
1055                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1056                b"\x02\x00",
1057            ),
1058            (
1059                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1060                b"\x02\x01\x80",
1061            ),
1062            (
1063                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1064                b"\x02\x02\xff\x80",
1065            ),
1066        ]);
1067    }
1068
1069    #[test]
1070    fn test_parse_bigint() {
1071        assert_parses::<BigInt<'_>>(&[
1072            (Ok(BigInt::new(b"\x80").unwrap()), b"\x02\x01\x80"),
1073            (Ok(BigInt::new(b"\xff").unwrap()), b"\x02\x01\xff"),
1074            (
1075                Ok(BigInt::new(b"\x00\xff\xff").unwrap()),
1076                b"\x02\x03\x00\xff\xff",
1077            ),
1078            (
1079                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1080                b"\x02\x02\xff\xff",
1081            ),
1082            (
1083                Ok(BigInt::new(b"\xff\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff").unwrap()),
1084                b"\x02\x0c\xff\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
1085            ),
1086            (
1087                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1088                b"\x02\x00",
1089            ),
1090        ]);
1091    }
1092
1093    #[test]
1094    fn test_parse_owned_bigint() {
1095        assert_parses::<OwnedBigInt>(&[
1096            (
1097                Ok(OwnedBigInt::new(b"\x80".to_vec()).unwrap()),
1098                b"\x02\x01\x80",
1099            ),
1100            (
1101                Ok(OwnedBigInt::new(b"\xff".to_vec()).unwrap()),
1102                b"\x02\x01\xff",
1103            ),
1104            (
1105                Ok(OwnedBigInt::new(b"\x00\xff\xff".to_vec()).unwrap()),
1106                b"\x02\x03\x00\xff\xff",
1107            ),
1108            (
1109                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1110                b"\x02\x02\xff\xff",
1111            ),
1112            (
1113                Ok(
1114                    OwnedBigInt::new(b"\xff\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff".to_vec())
1115                        .unwrap(),
1116                ),
1117                b"\x02\x0c\xff\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
1118            ),
1119            (
1120                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1121                b"\x02\x00",
1122            ),
1123        ]);
1124    }
1125
1126    #[test]
1127    fn test_parse_object_identifier() {
1128        assert_parses::<ObjectIdentifier>(&[
1129            (
1130                Ok(ObjectIdentifier::from_string("2.5").unwrap()),
1131                b"\x06\x01\x55",
1132            ),
1133            (
1134                Ok(ObjectIdentifier::from_string("2.5.2").unwrap()),
1135                b"\x06\x02\x55\x02",
1136            ),
1137            (
1138                Ok(ObjectIdentifier::from_string("1.2.840.113549").unwrap()),
1139                b"\x06\x06\x2a\x86\x48\x86\xf7\x0d",
1140            ),
1141            (
1142                Ok(ObjectIdentifier::from_string("1.2.3.4").unwrap()),
1143                b"\x06\x03\x2a\x03\x04",
1144            ),
1145            (
1146                Ok(ObjectIdentifier::from_string("1.2.840.133549.1.1.5").unwrap()),
1147                b"\x06\x09\x2a\x86\x48\x88\x93\x2d\x01\x01\x05",
1148            ),
1149            (
1150                Ok(ObjectIdentifier::from_string("2.100.3").unwrap()),
1151                b"\x06\x03\x81\x34\x03",
1152            ),
1153            (
1154                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1155                b"\x06\x00",
1156            ),
1157            (
1158                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1159                b"\x06\x07\x55\x02\xc0\x80\x80\x80\x80",
1160            ),
1161            (
1162                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1163                b"\x06\x02\x2a\x86",
1164            ),
1165        ]);
1166    }
1167
1168    #[test]
1169    fn test_parse_bit_string() {
1170        assert_parses::<BitString<'_>>(&[
1171            (Ok(BitString::new(b"", 0).unwrap()), b"\x03\x01\x00"),
1172            (Ok(BitString::new(b"\x00", 7).unwrap()), b"\x03\x02\x07\x00"),
1173            (Ok(BitString::new(b"\x80", 7).unwrap()), b"\x03\x02\x07\x80"),
1174            (
1175                Ok(BitString::new(b"\x81\xf0", 4).unwrap()),
1176                b"\x03\x03\x04\x81\xf0",
1177            ),
1178            (
1179                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1180                b"\x03\x00",
1181            ),
1182            (
1183                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1184                b"\x03\x02\x07\x01",
1185            ),
1186            (
1187                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1188                b"\x03\x02\x07\x40",
1189            ),
1190            (
1191                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1192                b"\x03\x02\x08\x00",
1193            ),
1194        ]);
1195    }
1196
1197    #[test]
1198    fn test_parse_owned_bit_string() {
1199        assert_parses::<OwnedBitString>(&[
1200            (Ok(OwnedBitString::new(vec![], 0).unwrap()), b"\x03\x01\x00"),
1201            (
1202                Ok(OwnedBitString::new(vec![0x00], 7).unwrap()),
1203                b"\x03\x02\x07\x00",
1204            ),
1205            (
1206                Ok(OwnedBitString::new(vec![0x80], 7).unwrap()),
1207                b"\x03\x02\x07\x80",
1208            ),
1209            (
1210                Ok(OwnedBitString::new(vec![0x81, 0xf0], 4).unwrap()),
1211                b"\x03\x03\x04\x81\xf0",
1212            ),
1213            (
1214                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1215                b"\x03\x00",
1216            ),
1217            (
1218                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1219                b"\x03\x02\x07\x01",
1220            ),
1221            (
1222                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1223                b"\x03\x02\x07\x40",
1224            ),
1225            (
1226                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1227                b"\x03\x02\x08\x00",
1228            ),
1229        ]);
1230    }
1231
1232    #[test]
1233    fn test_parse_printable_string() {
1234        assert_parses::<PrintableString<'_>>(&[
1235            (Ok(PrintableString::new("abc").unwrap()), b"\x13\x03abc"),
1236            (Ok(PrintableString::new(")").unwrap()), b"\x13\x01)"),
1237            (
1238                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1239                b"\x13\x03ab\x00",
1240            ),
1241        ]);
1242    }
1243
1244    #[test]
1245    fn test_parse_ia5string() {
1246        assert_parses::<IA5String<'_>>(&[
1247            (Ok(IA5String::new("abc").unwrap()), b"\x16\x03abc"),
1248            (Ok(IA5String::new(")").unwrap()), b"\x16\x01)"),
1249            (
1250                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1251                b"\x16\x03ab\xff",
1252            ),
1253        ]);
1254    }
1255
1256    #[test]
1257    fn test_parse_utf8string() {
1258        assert_parses::<Utf8String<'_>>(&[
1259            (Ok(Utf8String::new("abc")), b"\x0c\x03abc"),
1260            (Ok(Utf8String::new(")")), b"\x0c\x01)"),
1261            (
1262                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1263                b"\x0c\x01\xff",
1264            ),
1265        ]);
1266    }
1267
1268    #[test]
1269    fn test_parse_visiblestring() {
1270        assert_parses::<VisibleString<'_>>(&[
1271            (Ok(VisibleString::new("abc").unwrap()), b"\x1a\x03abc"),
1272            (Ok(VisibleString::new(")").unwrap()), b"\x1a\x01)"),
1273            (
1274                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1275                b"\x1a\x01\n",
1276            ),
1277        ]);
1278    }
1279
1280    #[test]
1281    fn test_parse_bmpstring() {
1282        assert_parses::<BMPString<'_>>(&[
1283            (
1284                Ok(BMPString::new(b"\x00a\x00b\x00c").unwrap()),
1285                b"\x1e\x06\x00a\x00b\x00c",
1286            ),
1287            (
1288                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1289                b"\x1e\x01a",
1290            ),
1291            (
1292                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1293                b"\x1e\x04\xde|X@",
1294            ),
1295            (
1296                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1297                b"\x1e\x02\xdeX",
1298            ),
1299        ]);
1300    }
1301
1302    #[test]
1303    fn test_parse_universalstring() {
1304        assert_parses::<UniversalString<'_>>(&[
1305            (
1306                Ok(UniversalString::new(b"\x00\x00\x00a\x00\x00\x00b\x00\x00\x00c").unwrap()),
1307                b"\x1c\x0c\x00\x00\x00a\x00\x00\x00b\x00\x00\x00c",
1308            ),
1309            (
1310                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1311                b"\x1c\x01a",
1312            ),
1313            (
1314                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1315                b"\x1c\x02ab",
1316            ),
1317            (
1318                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1319                b"\x1c\x03abc",
1320            ),
1321            (
1322                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1323                b"\x1c\x03abc",
1324            ),
1325            (
1326                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1327                b"\x1c\x04\x96\x8c\xeaU",
1328            ),
1329        ]);
1330    }
1331
1332    #[test]
1333    fn test_parse_utctime() {
1334        assert_parses::<UtcTime>(&[
1335            (
1336                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1337                b"\x17\x11910506164540-0700",
1338            ),
1339            (
1340                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1341                b"\x17\x11910506164540+0730",
1342            ),
1343            (
1344                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1345                b"\x17\x0f5105062345+0000",
1346            ),
1347            (
1348                Ok(UtcTime::new(DateTime::new(1991, 5, 6, 23, 45, 40).unwrap()).unwrap()),
1349                b"\x17\x0d910506234540Z",
1350            ),
1351            (
1352                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1353                b"\x17\x0b9105062345Z",
1354            ),
1355            (
1356                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1357                b"\x17\x0b5105062345Z",
1358            ),
1359            (
1360                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1361                b"\x17\x0da10506234540Z",
1362            ),
1363            (
1364                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1365                b"\x17\x0d91a506234540Z",
1366            ),
1367            (
1368                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1369                b"\x17\x0d9105a6234540Z",
1370            ),
1371            (
1372                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1373                b"\x17\x0d910506a34540Z",
1374            ),
1375            (
1376                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1377                b"\x17\x0d910506334a40Z",
1378            ),
1379            (
1380                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1381                b"\x17\x0d91050633444aZ",
1382            ),
1383            (
1384                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1385                b"\x17\x0d910506334461Z",
1386            ),
1387            (
1388                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1389                b"\x17\x0e910506334400Za",
1390            ),
1391            (
1392                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1393                b"\x17\x0d000100000000Z",
1394            ),
1395            (
1396                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1397                b"\x17\x0d101302030405Z",
1398            ),
1399            (
1400                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1401                b"\x17\x0d100002030405Z",
1402            ),
1403            (
1404                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1405                b"\x17\x0d100100030405Z",
1406            ),
1407            (
1408                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1409                b"\x17\x0d100132030405Z",
1410            ),
1411            (
1412                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1413                b"\x17\x0d100231030405Z",
1414            ),
1415            (
1416                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1417                b"\x17\x0d100102240405Z",
1418            ),
1419            (
1420                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1421                b"\x17\x0d100102036005Z",
1422            ),
1423            (
1424                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1425                b"\x17\x0d100102030460Z",
1426            ),
1427            (
1428                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1429                b"\x17\x0e-100102030410Z",
1430            ),
1431            (
1432                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1433                b"\x17\x0e10-0102030410Z",
1434            ),
1435            (
1436                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1437                b"\x17\x0e10-0002030410Z",
1438            ),
1439            (
1440                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1441                b"\x17\x0e1001-02030410Z",
1442            ),
1443            (
1444                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1445                b"\x17\x0e100102-030410Z",
1446            ),
1447            (
1448                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1449                b"\x17\x0e10010203-0410Z",
1450            ),
1451            (
1452                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1453                b"\x17\x0e1001020304-10Z",
1454            ),
1455            (
1456                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1457                b"\x17\x0c18102813516Z",
1458            ),
1459            (
1460                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1461                b"\x17\x1018102813516+0730",
1462            ),
1463            (
1464                // 2049 year with a negative UTC-offset, so actually a 2050
1465                // date. UTCTime doesn't support those.
1466                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1467                b"\x17\x0f4912311047-2026",
1468            ),
1469        ]);
1470    }
1471
1472    #[test]
1473    fn test_x509_generalizedtime() {
1474        assert_parses::<X509GeneralizedTime>(&[
1475            (
1476                Ok(X509GeneralizedTime::new(DateTime::new(2010, 1, 2, 3, 4, 5).unwrap()).unwrap()),
1477                b"\x18\x0f20100102030405Z",
1478            ),
1479            (
1480                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1481                b"\x18\x1320100102030405+0607",
1482            ),
1483            (
1484                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1485                b"\x18\x1320100102030405-0607",
1486            ),
1487            (
1488                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1489                b"\x18\x1320100602030405-0607",
1490            ),
1491            (
1492                // 29th of February (Leap Year)
1493                Ok(X509GeneralizedTime::new(DateTime::new(2000, 2, 29, 3, 4, 5).unwrap()).unwrap()),
1494                b"\x18\x0f20000229030405Z",
1495            ),
1496            (
1497                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1498                b"\x18\x0e20100102030405",
1499            ),
1500            (
1501                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1502                b"\x18\x0e00000100000000Z",
1503            ),
1504            (
1505                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1506                b"\x18\x0e20101302030405Z",
1507            ),
1508            (
1509                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1510                b"\x18\x0e20100002030405Z",
1511            ),
1512            (
1513                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1514                b"\x18\x0e20100100030405Z",
1515            ),
1516            (
1517                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1518                b"\x18\x0e20100132030405Z",
1519            ),
1520            (
1521                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1522                b"\x18\x0e20100231030405Z",
1523            ),
1524            (
1525                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1526                b"\x18\x0e20100102240405Z",
1527            ),
1528            (
1529                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1530                b"\x18\x0e20100102036005Z",
1531            ),
1532            (
1533                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1534                b"\x18\x0e20100102030460Z",
1535            ),
1536            (
1537                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1538                b"\x18\x0f-20100102030410Z",
1539            ),
1540            (
1541                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1542                b"\x18\x0f2010-0102030410Z",
1543            ),
1544            (
1545                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1546                b"\x18\x0f2010-0002030410Z",
1547            ),
1548            (
1549                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1550                b"\x18\x0f201001-02030410Z",
1551            ),
1552            (
1553                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1554                b"\x18\x0f20100102-030410Z",
1555            ),
1556            (
1557                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1558                b"\x18\x0f2010010203-0410Z",
1559            ),
1560            (
1561                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1562                b"\x18\x0f201001020304-10Z",
1563            ),
1564            (
1565                // 31st of June
1566                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1567                b"\x18\x1320100631030405-0607",
1568            ),
1569            (
1570                // 30th of February (Leap Year)
1571                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1572                b"\x18\x1320000230030405-0607",
1573            ),
1574            (
1575                // 29th of February (non-Leap Year)
1576                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1577                b"\x18\x1319000229030405-0607",
1578            ),
1579            (
1580                // Invalid timezone-offset hours
1581                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1582                b"\x18\x1319000228030405-3007",
1583            ),
1584            (
1585                // Invalid timezone-offset minutes
1586                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1587                b"\x18\x1319000228030405-2367",
1588            ),
1589            (
1590                // Trailing data
1591                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1592                b"\x18\x1019000228030405Z ",
1593            ),
1594            // Tests for fractional seconds, which we currently don't support
1595            (
1596                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1597                b"\x18\x1620100102030405.123456Z",
1598            ),
1599            (
1600                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1601                b"\x18\x1520100102030405.123456",
1602            ),
1603            (
1604                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1605                b"\x18\x1020100102030405.Z",
1606            ),
1607            (
1608                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1609                b"\x18\x0f20100102030405.",
1610            ),
1611            (
1612                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1613                b"\x18\x11-1\n110723459+1002",
1614            ),
1615            (
1616                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1617                b"\x18\x0d0 1204000060Z",
1618            ),
1619        ]);
1620    }
1621
1622    #[test]
1623    fn test_generalized_time() {
1624        assert_parses::<GeneralizedTime>(&[
1625            (
1626                // General case
1627                Ok(GeneralizedTime::new(
1628                    DateTime::new(2010, 1, 2, 3, 4, 5).unwrap(),
1629                    Some(123_456_000),
1630                )
1631                .unwrap()),
1632                b"\x18\x1620100102030405.123456Z",
1633            ),
1634            (
1635                // No fractional time
1636                Ok(
1637                    GeneralizedTime::new(DateTime::new(2010, 1, 2, 3, 4, 5).unwrap(), None)
1638                        .unwrap(),
1639                ),
1640                b"\x18\x0f20100102030405Z",
1641            ),
1642            (
1643                // Starting with 0 is ok
1644                Ok(GeneralizedTime::new(
1645                    DateTime::new(2010, 1, 2, 3, 4, 5).unwrap(),
1646                    Some(12_375_600),
1647                )
1648                .unwrap()),
1649                b"\x18\x1720100102030405.0123756Z",
1650            ),
1651            (
1652                // But ending with 0 is not OK
1653                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1654                b"\x18\x1220100102030405.10Z",
1655            ),
1656            (
1657                // Too many digits
1658                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1659                b"\x18\x1a20100102030405.0123456789Z",
1660            ),
1661            (
1662                // Missing timezone
1663                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1664                b"\x18\x1520100102030405.123456",
1665            ),
1666            (
1667                // Invalid fractional second
1668                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1669                b"\x18\x1020100102030405.Z",
1670            ),
1671        ])
1672    }
1673
1674    #[test]
1675    fn test_enumerated() {
1676        assert_parses::<Enumerated>(&[
1677            (Ok(Enumerated::new(12)), b"\x0a\x01\x0c"),
1678            (
1679                Err(ParseError::new(ParseErrorKind::InvalidValue)),
1680                b"\x0a\x09\xff\xff\xff\xff\xff\xff\xff\xff\xff",
1681            ),
1682        ]);
1683    }
1684
1685    #[test]
1686    fn test_parse_sequence() {
1687        assert_parses::<Sequence<'_>>(&[
1688            (
1689                Ok(Sequence::new(b"\x02\x01\x01\x02\x01\x02")),
1690                b"\x30\x06\x02\x01\x01\x02\x01\x02",
1691            ),
1692            (
1693                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1694                b"\x30\x04\x02\x01\x01",
1695            ),
1696            (
1697                Err(ParseError::new(ParseErrorKind::ExtraData)),
1698                b"\x30\x06\x02\x01\x01\x02\x01\x02\x00",
1699            ),
1700        ]);
1701    }
1702
1703    #[test]
1704    fn test_sequence_parse() {
1705        assert_parses_cb(
1706            &[
1707                (Ok((1, 2)), b"\x30\x06\x02\x01\x01\x02\x01\x02"),
1708                (
1709                    Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1710                    b"\x30\x03\x02\x01\x01",
1711                ),
1712                (
1713                    Err(ParseError::new(ParseErrorKind::ExtraData)),
1714                    b"\x30\x07\x02\x01\x01\x02\x01\x02\x00",
1715                ),
1716            ],
1717            |p| {
1718                p.read_element::<Sequence<'_>>()?
1719                    .parse(|p| Ok((p.read_element::<i64>()?, p.read_element::<i64>()?)))
1720            },
1721        );
1722    }
1723
1724    #[test]
1725    fn test_parse_is_empty() {
1726        assert_parses_cb(
1727            &[
1728                (
1729                    Ok(vec![1, 2, 3]),
1730                    b"\x30\x09\x02\x01\x01\x02\x01\x02\x02\x01\x03",
1731                ),
1732                (Ok(vec![]), b"\x30\x00"),
1733                (
1734                    Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1735                    b"\x30\x02\x02\x01",
1736                ),
1737            ],
1738            |p| {
1739                p.read_element::<Sequence<'_>>()?.parse(|p| {
1740                    let mut result = vec![];
1741                    while !p.is_empty() {
1742                        result.push(p.read_element::<i64>()?);
1743                    }
1744                    Ok(result)
1745                })
1746            },
1747        );
1748    }
1749
1750    #[test]
1751    fn test_parse_sequence_of() {
1752        assert_parses_cb(
1753            &[
1754                (
1755                    Ok(vec![1, 2, 3]),
1756                    b"\x30\x09\x02\x01\x01\x02\x01\x02\x02\x01\x03",
1757                ),
1758                (Ok(vec![]), b"\x30\x00"),
1759                (
1760                    Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })
1761                        .add_location(ParseLocation::Index(0))),
1762                    b"\x30\x02\x02\x01",
1763                ),
1764            ],
1765            |p| Ok(p.read_element::<SequenceOf<'_, i64>>()?.collect()),
1766        );
1767    }
1768
1769    #[test]
1770    fn test_sequence_of_constrained_lengths() {
1771        // Minimum only.
1772        assert_parses_cb(
1773            &[
1774                (
1775                    Ok(vec![1, 2, 3]),
1776                    b"\x30\x09\x02\x01\x01\x02\x01\x02\x02\x01\x03",
1777                ),
1778                (
1779                    Err(ParseError::new(ParseErrorKind::InvalidSize {
1780                        min: 1,
1781                        max: usize::MAX,
1782                        actual: 0,
1783                    })),
1784                    b"\x30\x00",
1785                ),
1786            ],
1787            |p| Ok(p.read_element::<SequenceOf<'_, i64, 1>>()?.collect()),
1788        );
1789
1790        // Minimum and maximum.
1791        assert_parses_cb(
1792            &[
1793                (
1794                    Err(ParseError::new(ParseErrorKind::InvalidSize {
1795                        min: 1,
1796                        max: 2,
1797                        actual: 3,
1798                    })),
1799                    b"\x30\x09\x02\x01\x01\x02\x01\x02\x02\x01\x03",
1800                ),
1801                (
1802                    Err(ParseError::new(ParseErrorKind::InvalidSize {
1803                        min: 1,
1804                        max: 2,
1805                        actual: 0,
1806                    })),
1807                    b"\x30\x00",
1808                ),
1809                (Ok(vec![3, 1]), b"\x30\x06\x02\x01\x03\x02\x01\x01"),
1810            ],
1811            |p| Ok(p.read_element::<SequenceOf<'_, i64, 1, 2>>()?.collect()),
1812        );
1813    }
1814
1815    #[test]
1816    fn parse_set_of() {
1817        assert_parses_cb(
1818            &[
1819                (
1820                    Ok(vec![1, 2, 3]),
1821                    b"\x31\x09\x02\x01\x01\x02\x01\x02\x02\x01\x03",
1822                ),
1823                (Ok(vec![]), b"\x31\x00"),
1824                (
1825                    Err(ParseError::new(ParseErrorKind::InvalidSetOrdering)
1826                        .add_location(ParseLocation::Index(1))),
1827                    b"\x31\x06\x02\x01\x03\x02\x01\x01",
1828                ),
1829                (
1830                    Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })
1831                        .add_location(ParseLocation::Index(0))),
1832                    b"\x31\x01\x02",
1833                ),
1834                (
1835                    Err(ParseError::new(ParseErrorKind::UnexpectedTag {
1836                        actual: Tag::primitive(0x1),
1837                    })
1838                    .add_location(ParseLocation::Index(0))),
1839                    b"\x31\x02\x01\x00",
1840                ),
1841            ],
1842            |p| Ok(p.read_element::<SetOf<'_, u64>>()?.collect()),
1843        );
1844    }
1845
1846    #[test]
1847    fn test_parse_optional() {
1848        assert_parses_cb(
1849            &[
1850                (Ok((Some(true), None)), b"\x01\x01\xff"),
1851                (Ok((Some(false), None)), b"\x01\x01\x00"),
1852                (Ok((None, Some(18))), b"\x02\x01\x12"),
1853                (Ok((Some(true), Some(18))), b"\x01\x01\xff\x02\x01\x12"),
1854                (Ok((None, None)), b""),
1855                (
1856                    Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1857                    b"\x01",
1858                ),
1859                (
1860                    Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1861                    b"\x02",
1862                ),
1863            ],
1864            |p| {
1865                Ok((
1866                    p.read_element::<Option<bool>>()?,
1867                    p.read_element::<Option<i64>>()?,
1868                ))
1869            },
1870        );
1871
1872        assert_parses::<Option<Tlv<'_>>>(&[
1873            (
1874                Ok(Some(Tlv {
1875                    tag: Tag::primitive(0x4),
1876                    data: b"abc",
1877                    full_data: b"\x04\x03abc",
1878                })),
1879                b"\x04\x03abc",
1880            ),
1881            (Ok(None), b""),
1882            (
1883                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1884                b"\x04",
1885            ),
1886        ]);
1887
1888        assert_parses::<Option<Choice2<u64, bool>>>(&[
1889            (Ok(None), b""),
1890            (Ok(Some(Choice2::ChoiceA(17))), b"\x02\x01\x11"),
1891            (Ok(Some(Choice2::ChoiceB(true))), b"\x01\x01\xff"),
1892            (Err(ParseError::new(ParseErrorKind::ExtraData)), b"\x03\x00"),
1893        ]);
1894    }
1895
1896    #[test]
1897    fn test_choice1() {
1898        assert_parses::<Choice1<bool>>(&[
1899            (Ok(Choice1::ChoiceA(true)), b"\x01\x01\xff"),
1900            (
1901                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
1902                    actual: Tag::primitive(0x03),
1903                })),
1904                b"\x03\x00",
1905            ),
1906            (
1907                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1908                b"",
1909            ),
1910        ]);
1911    }
1912
1913    #[test]
1914    fn test_choice2() {
1915        assert_parses::<Choice2<bool, i64>>(&[
1916            (Ok(Choice2::ChoiceA(true)), b"\x01\x01\xff"),
1917            (Ok(Choice2::ChoiceB(18)), b"\x02\x01\x12"),
1918            (
1919                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
1920                    actual: Tag::primitive(0x03),
1921                })),
1922                b"\x03\x00",
1923            ),
1924            (
1925                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1926                b"",
1927            ),
1928        ]);
1929    }
1930
1931    #[test]
1932    fn test_choice3() {
1933        assert_parses::<Choice3<bool, i64, ()>>(&[
1934            (Ok(Choice3::ChoiceA(true)), b"\x01\x01\xff"),
1935            (Ok(Choice3::ChoiceB(18)), b"\x02\x01\x12"),
1936            (Ok(Choice3::ChoiceC(())), b"\x05\x00"),
1937            (
1938                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
1939                    actual: Tag::primitive(0x03),
1940                })),
1941                b"\x03\x00",
1942            ),
1943            (
1944                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1945                b"",
1946            ),
1947        ]);
1948    }
1949
1950    #[test]
1951    fn test_parse_implicit() {
1952        assert_parses::<Implicit<bool, 2>>(&[
1953            (Ok(Implicit::new(true)), b"\x82\x01\xff"),
1954            (Ok(Implicit::new(false)), b"\x82\x01\x00"),
1955            (
1956                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
1957                    actual: Tag::primitive(0x01),
1958                })),
1959                b"\x01\x01\xff",
1960            ),
1961            (
1962                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
1963                    actual: Tag::primitive(0x02),
1964                })),
1965                b"\x02\x01\xff",
1966            ),
1967        ]);
1968        assert_parses::<Implicit<Sequence<'_>, 2>>(&[
1969            (Ok(Implicit::new(Sequence::new(b"abc"))), b"\xa2\x03abc"),
1970            (Ok(Implicit::new(Sequence::new(b""))), b"\xa2\x00"),
1971            (
1972                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
1973                    actual: Tag::primitive(0x01),
1974                })),
1975                b"\x01\x01\xff",
1976            ),
1977            (
1978                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
1979                    actual: Tag::primitive(0x02),
1980                })),
1981                b"\x02\x01\xff",
1982            ),
1983            (
1984                Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1985                b"",
1986            ),
1987        ]);
1988        assert_parses_cb(
1989            &[
1990                (Ok(true), b"\x82\x01\xff"),
1991                (Ok(false), b"\x82\x01\x00"),
1992                (
1993                    Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
1994                    b"",
1995                ),
1996                (
1997                    Err(ParseError::new(ParseErrorKind::UnexpectedTag {
1998                        actual: Tag::primitive(0x01),
1999                    })),
2000                    b"\x01\x01\xff",
2001                ),
2002                (
2003                    Err(ParseError::new(ParseErrorKind::UnexpectedTag {
2004                        actual: Tag::primitive(0x02),
2005                    })),
2006                    b"\x02\x01\xff",
2007                ),
2008            ],
2009            |p| p.read_implicit_element::<bool>(2),
2010        );
2011        assert_parses_cb(
2012            &[
2013                (Ok(Sequence::new(b"abc")), b"\xa2\x03abc"),
2014                (Ok(Sequence::new(b"")), b"\xa2\x00"),
2015                (
2016                    Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
2017                    b"",
2018                ),
2019                (
2020                    Err(ParseError::new(ParseErrorKind::UnexpectedTag {
2021                        actual: Tag::primitive(0x01),
2022                    })),
2023                    b"\x01\x01\xff",
2024                ),
2025                (
2026                    Err(ParseError::new(ParseErrorKind::UnexpectedTag {
2027                        actual: Tag::primitive(0x02),
2028                    })),
2029                    b"\x02\x01\xff",
2030                ),
2031            ],
2032            |p| p.read_implicit_element::<Sequence<'_>>(2),
2033        );
2034    }
2035
2036    #[test]
2037    fn test_parse_explicit() {
2038        assert_parses::<Explicit<bool, 2>>(&[
2039            (Ok(Explicit::new(true)), b"\xa2\x03\x01\x01\xff"),
2040            (Ok(Explicit::new(false)), b"\xa2\x03\x01\x01\x00"),
2041            (
2042                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
2043                    actual: Tag::primitive(0x01),
2044                })),
2045                b"\x01\x01\xff",
2046            ),
2047            (
2048                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
2049                    actual: Tag::primitive(0x02),
2050                })),
2051                b"\x02\x01\xff",
2052            ),
2053            (
2054                Err(ParseError::new(ParseErrorKind::UnexpectedTag {
2055                    actual: Tag::primitive(0x03),
2056                })),
2057                b"\xa2\x03\x03\x01\xff",
2058            ),
2059        ]);
2060        assert_parses_cb(
2061            &[
2062                (Ok(true), b"\xa2\x03\x01\x01\xff"),
2063                (Ok(false), b"\xa2\x03\x01\x01\x00"),
2064                (
2065                    Err(ParseError::new(ParseErrorKind::ShortData { needed: 1 })),
2066                    b"",
2067                ),
2068                (
2069                    Err(ParseError::new(ParseErrorKind::UnexpectedTag {
2070                        actual: Tag::primitive(0x01),
2071                    })),
2072                    b"\x01\x01\xff",
2073                ),
2074                (
2075                    Err(ParseError::new(ParseErrorKind::UnexpectedTag {
2076                        actual: Tag::primitive(0x03),
2077                    })),
2078                    b"\xa2\x03\x03\x01\xff",
2079                ),
2080            ],
2081            |p| p.read_explicit_element::<bool>(2),
2082        );
2083    }
2084
2085    #[test]
2086    fn test_parse_box() {
2087        assert_parses::<Box<u8>>(&[
2088            (Ok(Box::new(12u8)), b"\x02\x01\x0c"),
2089            (Ok(Box::new(0)), b"\x02\x01\x00"),
2090        ]);
2091    }
2092}