asn1/
types.rs

1#[cfg(not(feature = "std"))]
2use alloc::boxed::Box;
3#[cfg(not(feature = "std"))]
4use alloc::vec;
5#[cfg(not(feature = "std"))]
6use alloc::vec::Vec;
7use core::borrow::Borrow;
8use core::hash::{Hash, Hasher};
9use core::marker::PhantomData;
10use core::mem;
11use core::num::{
12    NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8,
13};
14
15use crate::writer::Writer;
16use crate::{
17    parse, parse_single, BitString, ObjectIdentifier, OwnedBitString, ParseError, ParseErrorKind,
18    ParseLocation, ParseResult, Parser, Tag, WriteBuf, WriteResult,
19};
20
21/// Any type that can be parsed as DER ASN.1.
22pub trait Asn1Readable<'a>: Sized {
23    /// Parse a value from the given parser.
24    ///
25    /// This method should read exactly one ASN.1 TLV from the parser,
26    /// consuming the appropriate bytes and returning the parsed value.
27    fn parse(parser: &mut Parser<'a>) -> ParseResult<Self>;
28
29    /// Returns whether this type can parse values with the given tag.
30    fn can_parse(tag: Tag) -> bool;
31}
32
33/// Types with a fixed-tag that can be parsed as DER ASN.1
34pub trait SimpleAsn1Readable<'a>: Sized {
35    /// The ASN.1 tag that this type expects when parsing.
36    const TAG: Tag;
37
38    /// Parse the value from the given data bytes.
39    ///
40    /// This method receives the value portion of a TLV (without the tag or
41    /// length) and should parse it into the appropriate type.
42    fn parse_data(data: &'a [u8]) -> ParseResult<Self>;
43}
44
45impl<'a, T: SimpleAsn1Readable<'a>> Asn1Readable<'a> for T {
46    #[inline]
47    fn parse(parser: &mut Parser<'a>) -> ParseResult<Self> {
48        let tlv = parser.read_tlv()?;
49        if !Self::can_parse(tlv.tag) {
50            return Err(ParseError::new(ParseErrorKind::UnexpectedTag {
51                actual: tlv.tag,
52            }));
53        }
54        Self::parse_data(tlv.data)
55    }
56
57    #[inline]
58    fn can_parse(tag: Tag) -> bool {
59        tag == Self::TAG
60    }
61}
62
63impl<'a, T: SimpleAsn1Readable<'a>> SimpleAsn1Readable<'a> for Box<T> {
64    const TAG: Tag = T::TAG;
65
66    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
67        Ok(Box::new(T::parse_data(data)?))
68    }
69}
70
71/// Any type that can be written as DER ASN.1.
72pub trait Asn1Writable: Sized {
73    /// Write this value to the given writer.
74    ///
75    /// This method should write the complete ASN.1 encoding of this value,
76    /// including the tag, length, and content bytes.
77    fn write(&self, dest: &mut Writer<'_>) -> WriteResult;
78
79    /// Get the complete encoded length (tag + length + content), if it can be
80    /// calculated efficiently.
81    ///
82    /// It is always safe to return `None`, which indicates the length is
83    /// unknown. Returning `Some(...)` from this method reduces the number of
84    /// re-allocations required in writing.
85    fn encoded_length(&self) -> Option<usize>;
86}
87
88/// Types with a fixed-tag that can be written as DER ASN.1.
89pub trait SimpleAsn1Writable: Sized {
90    /// The ASN.1 tag that this type uses when writing.
91    const TAG: Tag;
92
93    /// Write the value's data to the given buffer.
94    ///
95    /// This method should write only the value bytes (without the tag and
96    /// length) to the buffer.
97    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult;
98
99    /// Get the length of the data content (without tag and length bytes) if it
100    /// can be calculated efficiently.
101    ///
102    /// It is always safe to return `None`, which indicates the length is
103    /// unknown. Returning `Some(...)` from this method reduces the number of
104    /// re-allocations required in writing.
105    fn data_length(&self) -> Option<usize>;
106}
107
108/// A trait for types that can be parsed based on a `DEFINED BY` value.
109///
110/// `T` is the type of the `DEFINED BY` field (nearly always `ObjectIdentifier`).
111pub trait Asn1DefinedByReadable<'a, T: Asn1Readable<'a>>: Sized {
112    /// Parse a value based on the previously parsed item.
113    ///
114    /// The `item` parameter contains the value that determines how to parse
115    /// the current value from the parser.
116    fn parse(item: T, parser: &mut Parser<'a>) -> ParseResult<Self>;
117}
118
119/// A trait for types that can be written based on a `DEFINED BY` value.
120///
121/// `T` is the type of the `DEFINED BY` field (nearly always `ObjectIdentifier`).
122pub trait Asn1DefinedByWritable<T: Asn1Writable>: Sized {
123    /// Get a reference to the `DEFINED BY` value.
124    fn item(&self) -> &T;
125
126    /// Write this value to the given writer.
127    fn write(&self, dest: &mut Writer<'_>) -> WriteResult;
128
129    /// Get the complete encoded length (tag + length + content), if it can be
130    /// calculated efficiently.
131    ///
132    /// It is always safe to return `None`, which indicates the length is
133    /// unknown. Returning `Some(...)` from this method reduces the number of
134    /// re-allocations required in writing.
135    fn encoded_length(&self) -> Option<usize>;
136}
137
138impl<T: SimpleAsn1Writable> Asn1Writable for T {
139    #[inline]
140    fn write(&self, w: &mut Writer<'_>) -> WriteResult {
141        w.write_tlv(Self::TAG, self.data_length(), move |dest| {
142            self.write_data(dest)
143        })
144    }
145
146    fn encoded_length(&self) -> Option<usize> {
147        Some(Tlv::full_length(Self::TAG, self.data_length()?))
148    }
149}
150
151impl<T: SimpleAsn1Writable> SimpleAsn1Writable for &T {
152    const TAG: Tag = T::TAG;
153    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
154        T::write_data(self, dest)
155    }
156
157    fn data_length(&self) -> Option<usize> {
158        T::data_length(self)
159    }
160}
161
162impl<T: SimpleAsn1Writable> SimpleAsn1Writable for Box<T> {
163    const TAG: Tag = T::TAG;
164    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
165        T::write_data(self, dest)
166    }
167
168    fn data_length(&self) -> Option<usize> {
169        T::data_length(self)
170    }
171}
172
173/// A TLV (type, length, value) represented as the tag and bytes content.
174/// Generally used for parsing ASN.1 `ANY` values.
175#[derive(Debug, PartialEq, Hash, Clone, Copy, Eq)]
176pub struct Tlv<'a> {
177    pub(crate) tag: Tag,
178    // `data` is the value of a TLV
179    pub(crate) data: &'a [u8],
180    // `full_data` contains the encoded type and length, in addition to the
181    // value
182    pub(crate) full_data: &'a [u8],
183}
184
185impl<'a> Tlv<'a> {
186    pub(crate) fn full_length(t: Tag, inner_length: usize) -> usize {
187        t.encoded_length() + crate::writer::length_encoding_size(inner_length) + inner_length
188    }
189
190    /// The tag portion of a TLV.
191    pub fn tag(&self) -> Tag {
192        self.tag
193    }
194    /// The value portion of the TLV.
195    pub fn data(&self) -> &'a [u8] {
196        self.data
197    }
198    /// The full DER encoded TLV.
199    pub fn full_data(&self) -> &'a [u8] {
200        self.full_data
201    }
202    /// Parse this TLV as a given type.
203    pub fn parse<T: Asn1Readable<'a>>(&self) -> ParseResult<T> {
204        parse_single::<T>(self.full_data)
205    }
206}
207
208impl<'a> Asn1Readable<'a> for Tlv<'a> {
209    #[inline]
210    fn parse(parser: &mut Parser<'a>) -> ParseResult<Self> {
211        parser.read_tlv()
212    }
213
214    #[inline]
215    fn can_parse(_tag: Tag) -> bool {
216        true
217    }
218}
219impl Asn1Writable for Tlv<'_> {
220    #[inline]
221    fn write(&self, w: &mut Writer<'_>) -> WriteResult {
222        w.write_tlv(self.tag, Some(self.data.len()), move |dest| {
223            dest.push_slice(self.data)
224        })
225    }
226
227    fn encoded_length(&self) -> Option<usize> {
228        Some(Tlv::full_length(self.tag, self.data.len()))
229    }
230}
231
232impl Asn1Writable for &Tlv<'_> {
233    #[inline]
234    fn write(&self, w: &mut Writer<'_>) -> WriteResult {
235        Tlv::write(self, w)
236    }
237
238    fn encoded_length(&self) -> Option<usize> {
239        Tlv::encoded_length(self)
240    }
241}
242
243/// The ASN.1 NULL type, for use with `Parser.read_element` and
244/// `Writer.write_element`.
245pub type Null = ();
246
247impl SimpleAsn1Readable<'_> for Null {
248    const TAG: Tag = Tag::primitive(0x05);
249    #[inline]
250    fn parse_data(data: &[u8]) -> ParseResult<Null> {
251        if data.is_empty() {
252            Ok(())
253        } else {
254            Err(ParseError::new(ParseErrorKind::InvalidValue))
255        }
256    }
257}
258
259impl SimpleAsn1Writable for Null {
260    const TAG: Tag = Tag::primitive(0x05);
261    #[inline]
262    fn write_data(&self, _dest: &mut WriteBuf) -> WriteResult {
263        Ok(())
264    }
265
266    fn data_length(&self) -> Option<usize> {
267        Some(0)
268    }
269}
270
271impl SimpleAsn1Readable<'_> for bool {
272    const TAG: Tag = Tag::primitive(0x1);
273    fn parse_data(data: &[u8]) -> ParseResult<bool> {
274        match data {
275            b"\x00" => Ok(false),
276            b"\xff" => Ok(true),
277            _ => Err(ParseError::new(ParseErrorKind::InvalidValue)),
278        }
279    }
280}
281
282impl SimpleAsn1Writable for bool {
283    const TAG: Tag = Tag::primitive(0x1);
284    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
285        if *self {
286            dest.push_byte(0xff)
287        } else {
288            dest.push_byte(0x00)
289        }
290    }
291
292    fn data_length(&self) -> Option<usize> {
293        Some(1)
294    }
295}
296
297impl<'a> SimpleAsn1Readable<'a> for &'a [u8] {
298    const TAG: Tag = Tag::primitive(0x04);
299    fn parse_data(data: &'a [u8]) -> ParseResult<&'a [u8]> {
300        Ok(data)
301    }
302}
303
304impl SimpleAsn1Writable for &[u8] {
305    const TAG: Tag = Tag::primitive(0x04);
306    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
307        dest.push_slice(self)
308    }
309
310    fn data_length(&self) -> Option<usize> {
311        Some(self.len())
312    }
313}
314
315impl<const N: usize> SimpleAsn1Readable<'_> for [u8; N] {
316    const TAG: Tag = Tag::primitive(0x04);
317    fn parse_data(data: &[u8]) -> ParseResult<[u8; N]> {
318        data.try_into()
319            .map_err(|_| ParseError::new(ParseErrorKind::InvalidValue))
320    }
321}
322
323impl<const N: usize> SimpleAsn1Writable for [u8; N] {
324    const TAG: Tag = Tag::primitive(0x04);
325    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
326        dest.push_slice(self)
327    }
328
329    fn data_length(&self) -> Option<usize> {
330        Some(N)
331    }
332}
333
334/// Represents values that are encoded as an `OCTET STRING` containing an
335/// encoded TLV, of type `T`.
336#[derive(PartialEq, Eq, Debug)]
337pub struct OctetStringEncoded<T>(T);
338
339impl<T> OctetStringEncoded<T> {
340    pub fn new(v: T) -> OctetStringEncoded<T> {
341        OctetStringEncoded(v)
342    }
343
344    pub fn get(&self) -> &T {
345        &self.0
346    }
347
348    pub fn into_inner(self) -> T {
349        self.0
350    }
351}
352
353impl<'a, T: Asn1Readable<'a>> SimpleAsn1Readable<'a> for OctetStringEncoded<T> {
354    const TAG: Tag = Tag::primitive(0x04);
355    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
356        Ok(OctetStringEncoded::new(parse_single(data)?))
357    }
358}
359
360impl<T: Asn1Writable> SimpleAsn1Writable for OctetStringEncoded<T> {
361    const TAG: Tag = Tag::primitive(0x04);
362    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
363        self.0.write(&mut Writer::new(dest))
364    }
365
366    fn data_length(&self) -> Option<usize> {
367        self.0.encoded_length()
368    }
369}
370
371/// Type for use with `Parser.read_element` and `Writer.write_element` for
372/// handling ASN.1 `PrintableString`.  A `PrintableString` contains an `&str`
373/// with only valid characters.
374#[derive(Clone, Debug, PartialEq, Eq, Hash)]
375pub struct PrintableString<'a>(&'a str);
376
377impl<'a> PrintableString<'a> {
378    pub fn new(s: &'a str) -> Option<PrintableString<'a>> {
379        if PrintableString::verify(s.as_bytes()) {
380            Some(PrintableString(s))
381        } else {
382            None
383        }
384    }
385
386    fn new_from_bytes(s: &'a [u8]) -> Option<PrintableString<'a>> {
387        if PrintableString::verify(s) {
388            // TODO: This value is always valid utf-8 because we just verified
389            // the contents, but I don't want to call an unsafe function, so we
390            // end up validating it twice. If your profile says this is slow,
391            // now you know why.
392            Some(PrintableString(core::str::from_utf8(s).unwrap()))
393        } else {
394            None
395        }
396    }
397
398    pub fn as_str(&self) -> &'a str {
399        self.0
400    }
401
402    fn verify(data: &[u8]) -> bool {
403        for b in data {
404            match b {
405                b'A'..=b'Z'
406                | b'a'..=b'z'
407                | b'0'..=b'9'
408                | b' '
409                | b'\''
410                | b'('
411                | b')'
412                | b'+'
413                | b','
414                | b'-'
415                | b'.'
416                | b'/'
417                | b':'
418                | b'='
419                | b'?' => {}
420                _ => return false,
421            };
422        }
423        true
424    }
425}
426
427impl<'a> SimpleAsn1Readable<'a> for PrintableString<'a> {
428    const TAG: Tag = Tag::primitive(0x13);
429    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
430        PrintableString::new_from_bytes(data)
431            .ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
432    }
433}
434
435impl SimpleAsn1Writable for PrintableString<'_> {
436    const TAG: Tag = Tag::primitive(0x13);
437    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
438        dest.push_slice(self.0.as_bytes())
439    }
440
441    fn data_length(&self) -> Option<usize> {
442        Some(self.0.len())
443    }
444}
445
446/// Type for use with `Parser.read_element` and `Writer.write_element` for
447/// handling ASN.1 `IA5String`.  An `IA5String` contains an `&str`
448/// with only valid characters.
449#[derive(Clone, Debug, PartialEq, Eq)]
450pub struct IA5String<'a>(&'a str);
451
452impl<'a> IA5String<'a> {
453    pub fn new(s: &'a str) -> Option<IA5String<'a>> {
454        if IA5String::verify(s.as_bytes()) {
455            Some(IA5String(s))
456        } else {
457            None
458        }
459    }
460
461    fn new_from_bytes(s: &'a [u8]) -> Option<IA5String<'a>> {
462        if IA5String::verify(s) {
463            // TODO: This value is always valid utf-8 because we just verified
464            // the contents, but I don't want to call an unsafe function, so we
465            // end up validating it twice. If your profile says this is slow,
466            // now you know why.
467            Some(IA5String(core::str::from_utf8(s).unwrap()))
468        } else {
469            None
470        }
471    }
472
473    fn verify(s: &[u8]) -> bool {
474        s.is_ascii()
475    }
476
477    pub fn as_str(&self) -> &'a str {
478        self.0
479    }
480}
481
482impl<'a> SimpleAsn1Readable<'a> for IA5String<'a> {
483    const TAG: Tag = Tag::primitive(0x16);
484    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
485        IA5String::new_from_bytes(data).ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
486    }
487}
488impl SimpleAsn1Writable for IA5String<'_> {
489    const TAG: Tag = Tag::primitive(0x16);
490    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
491        dest.push_slice(self.0.as_bytes())
492    }
493
494    fn data_length(&self) -> Option<usize> {
495        Some(self.0.len())
496    }
497}
498
499/// Type for use with `Parser.read_element` and `Writer.write_element` for
500/// handling ASN.1 `UTF8String`.
501#[derive(Clone, Debug, PartialEq, Eq, Hash)]
502pub struct Utf8String<'a>(&'a str);
503
504impl<'a> Utf8String<'a> {
505    pub fn new(s: &'a str) -> Utf8String<'a> {
506        Utf8String(s)
507    }
508
509    fn new_from_bytes(s: &'a [u8]) -> Option<Utf8String<'a>> {
510        Some(Utf8String(core::str::from_utf8(s).ok()?))
511    }
512
513    pub fn as_str(&self) -> &'a str {
514        self.0
515    }
516}
517
518impl<'a> SimpleAsn1Readable<'a> for Utf8String<'a> {
519    const TAG: Tag = Tag::primitive(0x0c);
520    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
521        Utf8String::new_from_bytes(data)
522            .ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
523    }
524}
525impl SimpleAsn1Writable for Utf8String<'_> {
526    const TAG: Tag = Tag::primitive(0x0c);
527    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
528        dest.push_slice(self.0.as_bytes())
529    }
530
531    fn data_length(&self) -> Option<usize> {
532        Some(self.0.len())
533    }
534}
535
536/// Type for use with `Parser.read_element` and `Writer.write_element` for
537/// handling ASN.1 `VisibleString`.  A `VisibleString` contains an `&str`
538/// with only valid characters.
539#[derive(Clone, Debug, PartialEq, Eq)]
540pub struct VisibleString<'a>(&'a str);
541
542impl<'a> VisibleString<'a> {
543    pub fn new(s: &'a str) -> Option<VisibleString<'a>> {
544        if VisibleString::verify(s.as_bytes()) {
545            Some(VisibleString(s))
546        } else {
547            None
548        }
549    }
550
551    fn new_from_bytes(s: &'a [u8]) -> Option<VisibleString<'a>> {
552        if VisibleString::verify(s) {
553            // TODO: This value is always valid utf-8 because we just verified
554            // the contents, but I don't want to call an unsafe function, so we
555            // end up validating it twice. If your profile says this is slow,
556            // now you know why.
557            Some(VisibleString(core::str::from_utf8(s).unwrap()))
558        } else {
559            None
560        }
561    }
562
563    fn verify(s: &[u8]) -> bool {
564        for b in s {
565            if !(b.is_ascii_graphic() || *b == b' ') {
566                return false;
567            }
568        }
569        true
570    }
571
572    pub fn as_str(&self) -> &'a str {
573        self.0
574    }
575}
576
577impl<'a> SimpleAsn1Readable<'a> for VisibleString<'a> {
578    const TAG: Tag = Tag::primitive(0x1a);
579    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
580        VisibleString::new_from_bytes(data)
581            .ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
582    }
583}
584impl SimpleAsn1Writable for VisibleString<'_> {
585    const TAG: Tag = Tag::primitive(0x1a);
586    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
587        dest.push_slice(self.0.as_bytes())
588    }
589
590    fn data_length(&self) -> Option<usize> {
591        Some(self.0.len())
592    }
593}
594
595/// Type for use with `Parser.read_element` and `Writer.write_element` for
596/// handling ASN.1 `BMPString`. A `BMPString` contains encoded (UTF-16-BE)
597/// bytes which are known to be valid.
598#[derive(Debug, PartialEq, Clone, Eq, Hash)]
599pub struct BMPString<'a>(&'a [u8]);
600
601impl<'a> BMPString<'a> {
602    pub fn new(b: &'a [u8]) -> Option<BMPString<'a>> {
603        if BMPString::verify(b) {
604            Some(BMPString(b))
605        } else {
606            None
607        }
608    }
609
610    fn verify(b: &[u8]) -> bool {
611        if b.len() % 2 == 1 {
612            return false;
613        }
614
615        for r in core::char::decode_utf16(
616            b.chunks_exact(2)
617                .map(|v| u16::from_be_bytes(v.try_into().unwrap())),
618        ) {
619            if r.is_err() {
620                return false;
621            }
622        }
623
624        true
625    }
626
627    pub fn as_utf16_be_bytes(&self) -> &'a [u8] {
628        self.0
629    }
630}
631
632impl<'a> SimpleAsn1Readable<'a> for BMPString<'a> {
633    const TAG: Tag = Tag::primitive(0x1e);
634    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
635        BMPString::new(data).ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
636    }
637}
638impl SimpleAsn1Writable for BMPString<'_> {
639    const TAG: Tag = Tag::primitive(0x1e);
640    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
641        dest.push_slice(self.as_utf16_be_bytes())
642    }
643
644    fn data_length(&self) -> Option<usize> {
645        Some(self.as_utf16_be_bytes().len())
646    }
647}
648
649/// Type for use with `Parser.read_element` and `Writer.write_element` for
650/// handling ASN.1 `UniversalString`. A `UniversalString` contains encoded
651/// (UTF-32-BE) bytes which are known to be valid.
652#[derive(Debug, PartialEq, Clone, Eq, Hash)]
653pub struct UniversalString<'a>(&'a [u8]);
654
655impl<'a> UniversalString<'a> {
656    pub fn new(b: &'a [u8]) -> Option<UniversalString<'a>> {
657        if UniversalString::verify(b) {
658            Some(UniversalString(b))
659        } else {
660            None
661        }
662    }
663
664    fn verify(b: &[u8]) -> bool {
665        if b.len() % 4 != 0 {
666            return false;
667        }
668
669        for r in b
670            .chunks_exact(4)
671            .map(|v| u32::from_be_bytes(v.try_into().unwrap()))
672        {
673            if core::char::from_u32(r).is_none() {
674                return false;
675            }
676        }
677
678        true
679    }
680
681    pub fn as_utf32_be_bytes(&self) -> &'a [u8] {
682        self.0
683    }
684}
685
686impl<'a> SimpleAsn1Readable<'a> for UniversalString<'a> {
687    const TAG: Tag = Tag::primitive(0x1c);
688    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
689        UniversalString::new(data).ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
690    }
691}
692impl SimpleAsn1Writable for UniversalString<'_> {
693    const TAG: Tag = Tag::primitive(0x1c);
694    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
695        dest.push_slice(self.as_utf32_be_bytes())
696    }
697
698    fn data_length(&self) -> Option<usize> {
699        Some(self.as_utf32_be_bytes().len())
700    }
701}
702
703const fn validate_integer(data: &[u8], signed: bool) -> ParseResult<()> {
704    if data.is_empty() {
705        return Err(ParseError::new(ParseErrorKind::InvalidValue));
706    }
707    // Ensure integer is minimally encoded
708    if data.len() > 1
709        && ((data[0] == 0 && data[1] & 0x80 == 0) || (data[0] == 0xff && data[1] & 0x80 == 0x80))
710    {
711        return Err(ParseError::new(ParseErrorKind::InvalidValue));
712    }
713
714    // Reject negatives for unsigned types.
715    if !signed && data[0] & 0x80 == 0x80 {
716        return Err(ParseError::new(ParseErrorKind::InvalidValue));
717    }
718
719    Ok(())
720}
721
722macro_rules! impl_asn1_element_for_int {
723    ($t:ty; $signed:expr) => {
724        impl SimpleAsn1Readable<'_> for $t {
725            const TAG: Tag = Tag::primitive(0x02);
726            #[inline]
727            fn parse_data(mut data: &[u8]) -> ParseResult<Self> {
728                validate_integer(data, $signed)?;
729
730                // If we've got something like \x00\xff trim off the first \x00, since it's just
731                // there to not mark the value as a negative.
732                if !$signed && data.len() == mem::size_of::<Self>() + 1 && data[0] == 0 {
733                    data = &data[1..];
734                }
735                if data.len() > mem::size_of::<Self>() {
736                    return Err(ParseError::new(ParseErrorKind::IntegerOverflow));
737                }
738
739                let mut fixed_data = [0; mem::size_of::<$t>()];
740                fixed_data[mem::size_of::<Self>() - data.len()..].copy_from_slice(data);
741                let mut ret = Self::from_be_bytes(fixed_data);
742                // Shift up and down in order to sign extend the result.
743                ret <<= (8 * mem::size_of::<Self>()) - data.len() * 8;
744                ret >>= (8 * mem::size_of::<Self>()) - data.len() * 8;
745                Ok(ret)
746            }
747        }
748        impl SimpleAsn1Writable for $t {
749            const TAG: Tag = Tag::primitive(0x02);
750            fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
751                let num_bytes = self.data_length().unwrap() as u32;
752
753                for i in (1..=num_bytes).rev() {
754                    let digit = self.checked_shr((i - 1) * 8).unwrap_or(0);
755                    dest.push_byte(digit as u8)?;
756                }
757                Ok(())
758            }
759
760            fn data_length(&self) -> Option<usize> {
761                let mut num_bytes = 1;
762                let mut v: $t = *self;
763                #[allow(unused_comparisons)]
764                while v > 127 || ($signed && v < (-128i64) as $t) {
765                    num_bytes += 1;
766                    v = v.checked_shr(8).unwrap_or(0);
767                }
768                Some(num_bytes)
769            }
770        }
771    };
772}
773macro_rules! impl_asn1_write_for_nonzero_int {
774    ($t:ty, $inner_type:ty) => {
775        impl SimpleAsn1Writable for $t {
776            const TAG: Tag = <$inner_type as SimpleAsn1Writable>::TAG;
777
778            fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
779                <$inner_type>::from(*self).write_data(dest)
780            }
781
782            fn data_length(&self) -> Option<usize> {
783                <$inner_type>::from(*self).data_length()
784            }
785        }
786    };
787}
788
789impl_asn1_element_for_int!(i8; true);
790impl_asn1_element_for_int!(u8; false);
791impl_asn1_element_for_int!(i16; true);
792impl_asn1_element_for_int!(u16; false);
793impl_asn1_element_for_int!(i32; true);
794impl_asn1_element_for_int!(u32; false);
795impl_asn1_element_for_int!(i64; true);
796impl_asn1_element_for_int!(u64; false);
797
798impl_asn1_write_for_nonzero_int!(NonZeroI8, i8);
799impl_asn1_write_for_nonzero_int!(NonZeroI16, i16);
800impl_asn1_write_for_nonzero_int!(NonZeroI32, i32);
801impl_asn1_write_for_nonzero_int!(NonZeroI64, i64);
802impl_asn1_write_for_nonzero_int!(NonZeroU8, u8);
803impl_asn1_write_for_nonzero_int!(NonZeroU16, u16);
804impl_asn1_write_for_nonzero_int!(NonZeroU32, u32);
805impl_asn1_write_for_nonzero_int!(NonZeroU64, u64);
806
807/// Arbitrary sized unsigned integer. Contents may be accessed as `&[u8]` of
808/// big-endian data. Its contents always match the DER encoding of a value
809/// (i.e. they are minimal)
810#[derive(PartialEq, Clone, Copy, Debug, Hash, Eq)]
811pub struct BigUint<'a> {
812    data: &'a [u8],
813}
814
815impl<'a> BigUint<'a> {
816    /// Create a new `BigUint` from already encoded data. `data` must be encoded
817    /// as required by DER: minimally and if the high bit would be set in the
818    /// first octet, a leading `\x00` should be prepended (to disambiguate from
819    /// negative values).
820    pub const fn new(data: &'a [u8]) -> Option<Self> {
821        match validate_integer(data, false) {
822            Ok(()) => Some(BigUint { data }),
823            Err(_) => None,
824        }
825    }
826
827    /// Returns the contents of the integer as big-endian bytes.
828    pub fn as_bytes(&self) -> &'a [u8] {
829        self.data
830    }
831}
832
833impl<'a> SimpleAsn1Readable<'a> for BigUint<'a> {
834    const TAG: Tag = Tag::primitive(0x02);
835    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
836        BigUint::new(data).ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
837    }
838}
839impl SimpleAsn1Writable for BigUint<'_> {
840    const TAG: Tag = Tag::primitive(0x02);
841    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
842        dest.push_slice(self.as_bytes())
843    }
844
845    fn data_length(&self) -> Option<usize> {
846        Some(self.as_bytes().len())
847    }
848}
849
850/// Arbitrary sized unsigned integer which owns its data. Contents may be
851/// accessed as `&[u8]` of big-endian data. Its contents always match the DER
852/// encoding of a value (i.e. they are minimal)
853#[derive(PartialEq, Clone, Debug, Hash, Eq)]
854pub struct OwnedBigUint {
855    data: Vec<u8>,
856}
857
858impl OwnedBigUint {
859    /// Create a new `OwnedBigUint` from already encoded data. `data` must be
860    /// encoded as required by DER: minimally and if the high bit would be set
861    /// in the first octet, a leading `\x00` should be prepended (to
862    /// disambiguate from negative values).
863    pub fn new(data: Vec<u8>) -> Option<Self> {
864        validate_integer(&data, false).ok()?;
865        Some(OwnedBigUint { data })
866    }
867
868    /// Returns the contents of the integer as big-endian bytes.
869    pub fn as_bytes(&self) -> &[u8] {
870        &self.data
871    }
872}
873
874impl SimpleAsn1Readable<'_> for OwnedBigUint {
875    const TAG: Tag = Tag::primitive(0x02);
876    fn parse_data(data: &[u8]) -> ParseResult<Self> {
877        OwnedBigUint::new(data.to_vec())
878            .ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
879    }
880}
881impl SimpleAsn1Writable for OwnedBigUint {
882    const TAG: Tag = Tag::primitive(0x02);
883    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
884        dest.push_slice(self.as_bytes())
885    }
886
887    fn data_length(&self) -> Option<usize> {
888        Some(self.as_bytes().len())
889    }
890}
891
892/// Arbitrary sized signed integer. Contents may be accessed as `&[u8]` of
893/// big-endian data. Its contents always match the DER encoding of a value
894/// (i.e. they are minimal)
895#[derive(PartialEq, Clone, Copy, Debug, Hash, Eq)]
896pub struct BigInt<'a> {
897    data: &'a [u8],
898}
899
900impl<'a> BigInt<'a> {
901    /// Create a new `BigInt` from already encoded data. `data` must be encoded
902    /// as required by DER: minimally and if the high bit would be set in the
903    /// first octet, a leading `\x00` should be prepended (to disambiguate from
904    /// negative values).
905    pub const fn new(data: &'a [u8]) -> Option<Self> {
906        match validate_integer(data, true) {
907            Ok(()) => Some(BigInt { data }),
908            Err(_) => None,
909        }
910    }
911
912    /// Returns the contents of the integer as big-endian bytes.
913    pub fn as_bytes(&self) -> &'a [u8] {
914        self.data
915    }
916
917    /// Returns a boolean indicating whether the integer is negative.
918    pub fn is_negative(&self) -> bool {
919        self.data[0] & 0x80 == 0x80
920    }
921}
922
923impl<'a> SimpleAsn1Readable<'a> for BigInt<'a> {
924    const TAG: Tag = Tag::primitive(0x02);
925    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
926        BigInt::new(data).ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
927    }
928}
929impl SimpleAsn1Writable for BigInt<'_> {
930    const TAG: Tag = Tag::primitive(0x02);
931    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
932        dest.push_slice(self.as_bytes())
933    }
934
935    fn data_length(&self) -> Option<usize> {
936        Some(self.as_bytes().len())
937    }
938}
939
940/// Arbitrary sized signed integer which owns its contents. Contents may be
941/// accessed as `&[u8]` of big-endian data. Its contents always match the DER
942/// encoding of a value (i.e. they are minimal)
943#[derive(PartialEq, Clone, Debug, Hash, Eq)]
944pub struct OwnedBigInt {
945    data: Vec<u8>,
946}
947
948impl OwnedBigInt {
949    /// Create a new `OwnedBigInt` from already encoded data. `data` must be
950    /// encoded as required by DER: minimally and if the high bit would be set
951    /// in the first octet, a leading `\x00` should be prepended (to
952    /// disambiguate from negative values).
953    pub fn new(data: Vec<u8>) -> Option<Self> {
954        validate_integer(&data, true).ok()?;
955        Some(OwnedBigInt { data })
956    }
957
958    /// Returns the contents of the integer as big-endian bytes.
959    pub fn as_bytes(&self) -> &[u8] {
960        &self.data
961    }
962
963    /// Returns a boolean indicating whether the integer is negative.
964    pub fn is_negative(&self) -> bool {
965        self.data[0] & 0x80 == 0x80
966    }
967}
968
969impl SimpleAsn1Readable<'_> for OwnedBigInt {
970    const TAG: Tag = Tag::primitive(0x02);
971    fn parse_data(data: &[u8]) -> ParseResult<Self> {
972        OwnedBigInt::new(data.to_vec()).ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
973    }
974}
975impl SimpleAsn1Writable for OwnedBigInt {
976    const TAG: Tag = Tag::primitive(0x02);
977    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
978        dest.push_slice(self.as_bytes())
979    }
980
981    fn data_length(&self) -> Option<usize> {
982        Some(self.as_bytes().len())
983    }
984}
985
986impl<'a> SimpleAsn1Readable<'a> for ObjectIdentifier {
987    const TAG: Tag = Tag::primitive(0x06);
988    fn parse_data(data: &'a [u8]) -> ParseResult<ObjectIdentifier> {
989        ObjectIdentifier::from_der(data)
990    }
991}
992impl SimpleAsn1Writable for ObjectIdentifier {
993    const TAG: Tag = Tag::primitive(0x06);
994    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
995        dest.push_slice(self.as_der())
996    }
997    fn data_length(&self) -> Option<usize> {
998        Some(self.as_der().len())
999    }
1000}
1001
1002impl<'a> SimpleAsn1Readable<'a> for BitString<'a> {
1003    const TAG: Tag = Tag::primitive(0x03);
1004    fn parse_data(data: &'a [u8]) -> ParseResult<BitString<'a>> {
1005        if data.is_empty() {
1006            return Err(ParseError::new(ParseErrorKind::InvalidValue));
1007        }
1008        BitString::new(&data[1..], data[0])
1009            .ok_or_else(|| ParseError::new(ParseErrorKind::InvalidValue))
1010    }
1011}
1012impl SimpleAsn1Writable for BitString<'_> {
1013    const TAG: Tag = Tag::primitive(0x03);
1014    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1015        dest.push_byte(self.padding_bits())?;
1016        dest.push_slice(self.as_bytes())
1017    }
1018
1019    fn data_length(&self) -> Option<usize> {
1020        Some(1 + self.as_bytes().len())
1021    }
1022}
1023impl<'a> SimpleAsn1Readable<'a> for OwnedBitString {
1024    const TAG: Tag = Tag::primitive(0x03);
1025    fn parse_data(data: &'a [u8]) -> ParseResult<OwnedBitString> {
1026        let bs = BitString::parse_data(data)?;
1027        Ok(OwnedBitString::new(bs.as_bytes().to_vec(), bs.padding_bits()).unwrap())
1028    }
1029}
1030impl SimpleAsn1Writable for OwnedBitString {
1031    const TAG: Tag = Tag::primitive(0x03);
1032    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1033        self.as_bitstring().write_data(dest)
1034    }
1035
1036    fn data_length(&self) -> Option<usize> {
1037        self.as_bitstring().data_length()
1038    }
1039}
1040
1041fn read_byte(data: &mut &[u8]) -> ParseResult<u8> {
1042    if data.is_empty() {
1043        return Err(ParseError::new(ParseErrorKind::InvalidValue));
1044    }
1045    let result = Ok(data[0]);
1046    *data = &data[1..];
1047    result
1048}
1049
1050fn read_digit(data: &mut &[u8]) -> ParseResult<u8> {
1051    let b = read_byte(data)?;
1052    if !b.is_ascii_digit() {
1053        return Err(ParseError::new(ParseErrorKind::InvalidValue));
1054    }
1055    Ok(b - b'0')
1056}
1057
1058fn read_2_digits(data: &mut &[u8]) -> ParseResult<u8> {
1059    Ok(read_digit(data)? * 10 + read_digit(data)?)
1060}
1061
1062fn read_4_digits(data: &mut &[u8]) -> ParseResult<u16> {
1063    Ok(u16::from(read_digit(data)?) * 1000
1064        + u16::from(read_digit(data)?) * 100
1065        + u16::from(read_digit(data)?) * 10
1066        + u16::from(read_digit(data)?))
1067}
1068
1069const fn validate_date(year: u16, month: u8, day: u8) -> ParseResult<()> {
1070    if day < 1 {
1071        return Err(ParseError::new(ParseErrorKind::InvalidValue));
1072    }
1073    let days_in_month = match month {
1074        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1075        4 | 6 | 9 | 11 => 30,
1076        2 => {
1077            if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
1078                29
1079            } else {
1080                28
1081            }
1082        }
1083        _ => return Err(ParseError::new(ParseErrorKind::InvalidValue)),
1084    };
1085    if day > days_in_month {
1086        return Err(ParseError::new(ParseErrorKind::InvalidValue));
1087    }
1088
1089    Ok(())
1090}
1091
1092fn read_tz_and_finish(data: &mut &[u8]) -> ParseResult<()> {
1093    if read_byte(data)? != b'Z' {
1094        return Err(ParseError::new(ParseErrorKind::InvalidValue));
1095    }
1096
1097    if !data.is_empty() {
1098        return Err(ParseError::new(ParseErrorKind::InvalidValue));
1099    }
1100    Ok(())
1101}
1102
1103fn push_two_digits(dest: &mut WriteBuf, val: u8) -> WriteResult {
1104    dest.push_byte(b'0' + ((val / 10) % 10))?;
1105    dest.push_byte(b'0' + (val % 10))
1106}
1107
1108fn push_four_digits(dest: &mut WriteBuf, val: u16) -> WriteResult {
1109    dest.push_byte(b'0' + ((val / 1000) % 10) as u8)?;
1110    dest.push_byte(b'0' + ((val / 100) % 10) as u8)?;
1111    dest.push_byte(b'0' + ((val / 10) % 10) as u8)?;
1112    dest.push_byte(b'0' + (val % 10) as u8)
1113}
1114
1115/// A structure representing a (UTC timezone) date and time.
1116/// Wrapped by `UtcTime` and `X509GeneralizedTime` and used in
1117/// `GeneralizedTime`.
1118#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd)]
1119pub struct DateTime {
1120    year: u16,
1121    month: u8,
1122    day: u8,
1123    hour: u8,
1124    minute: u8,
1125    second: u8,
1126}
1127
1128impl DateTime {
1129    pub const fn new(
1130        year: u16,
1131        month: u8,
1132        day: u8,
1133        hour: u8,
1134        minute: u8,
1135        second: u8,
1136    ) -> ParseResult<DateTime> {
1137        if hour > 23 || minute > 59 || second > 59 {
1138            return Err(ParseError::new(ParseErrorKind::InvalidValue));
1139        }
1140        match validate_date(year, month, day) {
1141            Ok(()) => Ok(DateTime {
1142                year,
1143                month,
1144                day,
1145                hour,
1146                minute,
1147                second,
1148            }),
1149            Err(e) => Err(e),
1150        }
1151    }
1152
1153    /// The calendar year.
1154    pub fn year(&self) -> u16 {
1155        self.year
1156    }
1157
1158    /// The calendar month (1 to 12).
1159    pub fn month(&self) -> u8 {
1160        self.month
1161    }
1162
1163    /// The calendar day (1 to 31).
1164    pub fn day(&self) -> u8 {
1165        self.day
1166    }
1167
1168    /// The clock hour (0 to 23).
1169    pub fn hour(&self) -> u8 {
1170        self.hour
1171    }
1172
1173    /// The clock minute (0 to 59).
1174    pub fn minute(&self) -> u8 {
1175        self.minute
1176    }
1177
1178    /// The clock second (0 to 59).
1179    pub fn second(&self) -> u8 {
1180        self.second
1181    }
1182}
1183
1184/// Used for parsing and writing ASN.1 `UTC TIME` values. Wraps a
1185/// `DateTime`.
1186#[derive(Debug, Clone, PartialEq, Hash, Eq)]
1187pub struct UtcTime(DateTime);
1188
1189impl UtcTime {
1190    pub fn new(dt: DateTime) -> ParseResult<UtcTime> {
1191        if dt.year() < 1950 || dt.year() >= 2050 {
1192            return Err(ParseError::new(ParseErrorKind::InvalidValue));
1193        }
1194        Ok(UtcTime(dt))
1195    }
1196
1197    pub fn as_datetime(&self) -> &DateTime {
1198        &self.0
1199    }
1200}
1201
1202impl SimpleAsn1Readable<'_> for UtcTime {
1203    const TAG: Tag = Tag::primitive(0x17);
1204    fn parse_data(mut data: &[u8]) -> ParseResult<Self> {
1205        let year = u16::from(read_2_digits(&mut data)?);
1206        let month = read_2_digits(&mut data)?;
1207        let day = read_2_digits(&mut data)?;
1208        // UTCTime only encodes times prior to 2050. We use the X.509 mapping of two-digit
1209        // year ordinals to full year:
1210        // https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
1211        let year = if year >= 50 { 1900 + year } else { 2000 + year };
1212        let hour = read_2_digits(&mut data)?;
1213        let minute = read_2_digits(&mut data)?;
1214        let second = read_2_digits(&mut data)?;
1215
1216        read_tz_and_finish(&mut data)?;
1217
1218        UtcTime::new(DateTime::new(year, month, day, hour, minute, second)?)
1219    }
1220}
1221
1222impl SimpleAsn1Writable for UtcTime {
1223    const TAG: Tag = Tag::primitive(0x17);
1224    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1225        let dt = self.as_datetime();
1226        let year = if 1950 <= dt.year() && dt.year() < 2000 {
1227            dt.year() - 1900
1228        } else {
1229            assert!(2000 <= dt.year() && dt.year() < 2050);
1230            dt.year() - 2000
1231        };
1232        push_two_digits(dest, year.try_into().unwrap())?;
1233        push_two_digits(dest, dt.month())?;
1234        push_two_digits(dest, dt.day())?;
1235
1236        push_two_digits(dest, dt.hour())?;
1237        push_two_digits(dest, dt.minute())?;
1238        push_two_digits(dest, dt.second())?;
1239
1240        dest.push_byte(b'Z')
1241    }
1242
1243    fn data_length(&self) -> Option<usize> {
1244        Some(13)
1245    }
1246}
1247
1248/// Used for parsing and writing ASN.1 `GENERALIZED TIME` values used in X.509.
1249/// Wraps a `DateTime`.
1250#[derive(Debug, Clone, PartialEq, Hash, Eq)]
1251pub struct X509GeneralizedTime(DateTime);
1252
1253impl X509GeneralizedTime {
1254    pub fn new(dt: DateTime) -> ParseResult<X509GeneralizedTime> {
1255        Ok(X509GeneralizedTime(dt))
1256    }
1257
1258    pub fn as_datetime(&self) -> &DateTime {
1259        &self.0
1260    }
1261}
1262
1263impl SimpleAsn1Readable<'_> for X509GeneralizedTime {
1264    const TAG: Tag = Tag::primitive(0x18);
1265    fn parse_data(mut data: &[u8]) -> ParseResult<X509GeneralizedTime> {
1266        let year = read_4_digits(&mut data)?;
1267        let month = read_2_digits(&mut data)?;
1268        let day = read_2_digits(&mut data)?;
1269        let hour = read_2_digits(&mut data)?;
1270        let minute = read_2_digits(&mut data)?;
1271        let second = read_2_digits(&mut data)?;
1272
1273        // Fractionals are forbidden (RFC5280)
1274
1275        read_tz_and_finish(&mut data)?;
1276
1277        X509GeneralizedTime::new(DateTime::new(year, month, day, hour, minute, second)?)
1278    }
1279}
1280
1281impl SimpleAsn1Writable for X509GeneralizedTime {
1282    const TAG: Tag = Tag::primitive(0x18);
1283    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1284        let dt = self.as_datetime();
1285        push_four_digits(dest, dt.year())?;
1286        push_two_digits(dest, dt.month())?;
1287        push_two_digits(dest, dt.day())?;
1288
1289        push_two_digits(dest, dt.hour())?;
1290        push_two_digits(dest, dt.minute())?;
1291        push_two_digits(dest, dt.second())?;
1292
1293        dest.push_byte(b'Z')
1294    }
1295
1296    fn data_length(&self) -> Option<usize> {
1297        Some(15) // YYYYMMDDHHMMSSZ
1298    }
1299}
1300
1301/// Used for parsing and writing ASN.1 `GENERALIZED TIME` values,
1302/// including values with fractional seconds of up to nanosecond
1303/// precision.
1304#[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Eq)]
1305pub struct GeneralizedTime {
1306    datetime: DateTime,
1307    nanoseconds: Option<u32>,
1308}
1309
1310impl GeneralizedTime {
1311    pub fn new(dt: DateTime, nanoseconds: Option<u32>) -> ParseResult<GeneralizedTime> {
1312        if let Some(val) = nanoseconds {
1313            if val < 1 || val >= 1e9 as u32 {
1314                return Err(ParseError::new(ParseErrorKind::InvalidValue));
1315            }
1316        }
1317
1318        Ok(GeneralizedTime {
1319            datetime: dt,
1320            nanoseconds,
1321        })
1322    }
1323
1324    pub fn as_datetime(&self) -> &DateTime {
1325        &self.datetime
1326    }
1327
1328    pub fn nanoseconds(&self) -> Option<u32> {
1329        self.nanoseconds
1330    }
1331}
1332
1333fn read_fractional_time(data: &mut &[u8]) -> ParseResult<Option<u32>> {
1334    // We cannot use read_byte here because it will advance the pointer
1335    // However, we know that the is suffixed by 'Z' so reading into an empty
1336    // data should lead to an error.
1337    if data.first() == Some(&b'.') {
1338        *data = &data[1..];
1339
1340        let mut fraction = 0u32;
1341        let mut digits = 0;
1342        // Read up to 9 digits
1343        for b in data.iter().take(9) {
1344            if !b.is_ascii_digit() {
1345                if digits == 0 {
1346                    // We must have at least one digit
1347                    return Err(ParseError::new(ParseErrorKind::InvalidValue));
1348                }
1349                break;
1350            }
1351            fraction = fraction * 10 + (b - b'0') as u32;
1352            digits += 1;
1353        }
1354        *data = &data[digits..];
1355
1356        // No trailing zero
1357        if fraction % 10 == 0 {
1358            return Err(ParseError::new(ParseErrorKind::InvalidValue));
1359        }
1360
1361        // Now let scale up in nanoseconds
1362        let nanoseconds: u32 = fraction * 10u32.pow(9 - digits as u32);
1363        Ok(Some(nanoseconds))
1364    } else {
1365        Ok(None)
1366    }
1367}
1368
1369impl SimpleAsn1Readable<'_> for GeneralizedTime {
1370    const TAG: Tag = Tag::primitive(0x18);
1371    fn parse_data(mut data: &[u8]) -> ParseResult<GeneralizedTime> {
1372        let year = read_4_digits(&mut data)?;
1373        let month = read_2_digits(&mut data)?;
1374        let day = read_2_digits(&mut data)?;
1375        let hour = read_2_digits(&mut data)?;
1376        let minute = read_2_digits(&mut data)?;
1377        let second = read_2_digits(&mut data)?;
1378
1379        let fraction = read_fractional_time(&mut data)?;
1380        read_tz_and_finish(&mut data)?;
1381
1382        GeneralizedTime::new(
1383            DateTime::new(year, month, day, hour, minute, second)?,
1384            fraction,
1385        )
1386    }
1387}
1388
1389impl SimpleAsn1Writable for GeneralizedTime {
1390    const TAG: Tag = Tag::primitive(0x18);
1391    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1392        let dt = self.as_datetime();
1393        push_four_digits(dest, dt.year())?;
1394        push_two_digits(dest, dt.month())?;
1395        push_two_digits(dest, dt.day())?;
1396
1397        push_two_digits(dest, dt.hour())?;
1398        push_two_digits(dest, dt.minute())?;
1399        push_two_digits(dest, dt.second())?;
1400
1401        if let Some(nanoseconds) = self.nanoseconds() {
1402            dest.push_byte(b'.')?;
1403
1404            let mut buf = itoa::Buffer::new();
1405            let nanos = buf.format(nanoseconds);
1406            let pad = 9 - nanos.len();
1407            let nanos = nanos.trim_end_matches('0');
1408
1409            for _ in 0..pad {
1410                dest.push_byte(b'0')?;
1411            }
1412
1413            dest.push_slice(nanos.as_bytes())?;
1414        }
1415
1416        dest.push_byte(b'Z')
1417    }
1418
1419    fn data_length(&self) -> Option<usize> {
1420        let base_len = 15; // YYYYMMDDHHMMSSZ
1421        if let Some(nanoseconds) = self.nanoseconds() {
1422            let mut buf = itoa::Buffer::new();
1423            let nanos = buf.format(nanoseconds);
1424            let pad = 9 - nanos.len();
1425            let nanos = nanos.trim_end_matches('0');
1426            Some(base_len + 1 + pad + nanos.len()) // . + padded nanos
1427        } else {
1428            Some(base_len)
1429        }
1430    }
1431}
1432
1433/// An ASN.1 `ENUMERATED` value.
1434#[derive(Debug, PartialEq, Eq)]
1435pub struct Enumerated(u32);
1436
1437impl Enumerated {
1438    pub fn new(v: u32) -> Enumerated {
1439        Enumerated(v)
1440    }
1441
1442    pub fn value(&self) -> u32 {
1443        self.0
1444    }
1445}
1446
1447impl<'a> SimpleAsn1Readable<'a> for Enumerated {
1448    const TAG: Tag = Tag::primitive(0xa);
1449
1450    fn parse_data(data: &'a [u8]) -> ParseResult<Enumerated> {
1451        Ok(Enumerated::new(u32::parse_data(data)?))
1452    }
1453}
1454
1455impl SimpleAsn1Writable for Enumerated {
1456    const TAG: Tag = Tag::primitive(0xa);
1457
1458    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1459        u32::write_data(&self.value(), dest)
1460    }
1461
1462    fn data_length(&self) -> Option<usize> {
1463        self.value().data_length()
1464    }
1465}
1466
1467impl<'a, T: Asn1Readable<'a>> Asn1Readable<'a> for Option<T> {
1468    fn parse(parser: &mut Parser<'a>) -> ParseResult<Self> {
1469        match parser.peek_tag() {
1470            Some(tag) if Self::can_parse(tag) => Ok(Some(parser.read_element::<T>()?)),
1471            Some(_) | None => Ok(None),
1472        }
1473    }
1474
1475    #[inline]
1476    fn can_parse(tag: Tag) -> bool {
1477        T::can_parse(tag)
1478    }
1479}
1480
1481impl<T: Asn1Writable> Asn1Writable for Option<T> {
1482    #[inline]
1483    fn write(&self, w: &mut Writer<'_>) -> WriteResult {
1484        if let Some(v) = self {
1485            w.write_element(v)
1486        } else {
1487            Ok(())
1488        }
1489    }
1490
1491    fn encoded_length(&self) -> Option<usize> {
1492        match self {
1493            Some(v) => v.encoded_length(),
1494            None => Some(0),
1495        }
1496    }
1497}
1498
1499macro_rules! declare_choice {
1500    ($count:ident => $(($number:ident $name:ident)),+) => {
1501        /// Represents an ASN.1 `CHOICE` with the provided number of potential
1502        /// types.
1503        ///
1504        /// If you need more variants than are provided, please file an issue
1505        /// or submit a pull request! Arbitrary numbers of variants are
1506        /// supported by the `#[derive(asn1::Asn1Read)]` and
1507        /// `#[derive(asn1::Asn1Write)]` APIs.
1508        #[derive(Debug, PartialEq, Eq)]
1509        pub enum $count<
1510            $($number,)+
1511        > {
1512            $(
1513                $name($number),
1514            )*
1515        }
1516
1517        impl<
1518            'a,
1519            $(
1520                $number: Asn1Readable<'a>,
1521            )*
1522        > Asn1Readable<'a> for $count<$($number,)+> {
1523            fn parse(parser: &mut Parser<'a>) -> ParseResult<Self> {
1524                let tlv = parser.read_tlv()?;
1525                $(
1526                    if $number::can_parse(tlv.tag()) {
1527                        return Ok($count::$name(tlv.parse::<$number>()?));
1528                    }
1529                )+
1530                Err(ParseError::new(ParseErrorKind::UnexpectedTag{actual: tlv.tag()}))
1531            }
1532
1533            fn can_parse(tag: Tag) -> bool {
1534                $(
1535                    if $number::can_parse(tag) {
1536                        return true;
1537                    }
1538                )+
1539                false
1540            }
1541        }
1542
1543        impl<
1544            $(
1545                $number: Asn1Writable,
1546            )+
1547        > Asn1Writable for $count<$($number,)+> {
1548            fn write(&self, w: &mut Writer<'_>) -> WriteResult {
1549                match self {
1550                    $(
1551                        $count::$name(v) => w.write_element(v),
1552                    )+
1553                }
1554            }
1555
1556            fn encoded_length(&self) -> Option<usize> {
1557                match self {
1558                    $(
1559                        $count::$name(v) => Asn1Writable::encoded_length(v),
1560                    )+
1561                }
1562            }
1563        }
1564    }
1565}
1566
1567declare_choice!(Choice1 => (T1 ChoiceA));
1568declare_choice!(Choice2 => (T1 ChoiceA), (T2 ChoiceB));
1569declare_choice!(Choice3 => (T1 ChoiceA), (T2 ChoiceB), (T3 ChoiceC));
1570
1571/// Represents an ASN.1 `SEQUENCE`.
1572///
1573/// By itself, this merely indicates a sequence of bytes that are claimed to
1574// form an ASN1 sequence. In almost any circumstance, you'll want to
1575/// immediately call `Sequence.parse` on this value to decode the actual
1576/// contents therein.
1577#[derive(Debug, PartialEq, Hash, Clone, Eq)]
1578pub struct Sequence<'a> {
1579    data: &'a [u8],
1580}
1581
1582impl<'a> Sequence<'a> {
1583    #[inline]
1584    pub(crate) fn new(data: &'a [u8]) -> Sequence<'a> {
1585        Sequence { data }
1586    }
1587
1588    /// Parses the contents of the `Sequence`. Behaves the same as the module-level `parse`
1589    /// function.
1590    pub fn parse<T, E: From<ParseError>, F: Fn(&mut Parser<'a>) -> Result<T, E>>(
1591        self,
1592        f: F,
1593    ) -> Result<T, E> {
1594        parse(self.data, f)
1595    }
1596}
1597
1598impl<'a> SimpleAsn1Readable<'a> for Sequence<'a> {
1599    const TAG: Tag = Tag::constructed(0x10);
1600    #[inline]
1601    fn parse_data(data: &'a [u8]) -> ParseResult<Sequence<'a>> {
1602        Ok(Sequence::new(data))
1603    }
1604}
1605impl SimpleAsn1Writable for Sequence<'_> {
1606    const TAG: Tag = Tag::constructed(0x10);
1607    #[inline]
1608    fn write_data(&self, data: &mut WriteBuf) -> WriteResult {
1609        data.push_slice(self.data)
1610    }
1611
1612    fn data_length(&self) -> Option<usize> {
1613        Some(self.data.len())
1614    }
1615}
1616
1617/// Writes an ASN.1 `SEQUENCE` using a callback that writes the inner
1618/// elements.
1619pub struct SequenceWriter<'a> {
1620    f: &'a dyn Fn(&mut Writer<'_>) -> WriteResult,
1621}
1622
1623impl<'a> SequenceWriter<'a> {
1624    #[inline]
1625    pub fn new(f: &'a dyn Fn(&mut Writer<'_>) -> WriteResult) -> Self {
1626        SequenceWriter { f }
1627    }
1628}
1629
1630impl SimpleAsn1Writable for SequenceWriter<'_> {
1631    const TAG: Tag = Tag::constructed(0x10);
1632    #[inline]
1633    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1634        (self.f)(&mut Writer::new(dest))
1635    }
1636
1637    fn data_length(&self) -> Option<usize> {
1638        None
1639    }
1640}
1641
1642/// Represents an ASN.1 `SEQUENCE OF`. This is an `Iterator` over values that
1643/// are decoded.
1644pub struct SequenceOf<
1645    'a,
1646    T,
1647    const MINIMUM_LEN: usize = 0,
1648    const MAXIMUM_LEN: usize = { usize::MAX },
1649> {
1650    parser: Parser<'a>,
1651    length: usize,
1652    _phantom: PhantomData<T>,
1653}
1654
1655impl<'a, T: Asn1Readable<'a>, const MINIMUM_LEN: usize, const MAXIMUM_LEN: usize>
1656    SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN>
1657{
1658    #[inline]
1659    pub(crate) fn new(data: &'a [u8]) -> ParseResult<SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN>> {
1660        let length = parse(data, |p| {
1661            let mut i = 0;
1662            while !p.is_empty() {
1663                p.read_element::<T>()
1664                    .map_err(|e| e.add_location(ParseLocation::Index(i)))?;
1665                i += 1;
1666            }
1667            Ok(i)
1668        })?;
1669
1670        if length < MINIMUM_LEN || length > MAXIMUM_LEN {
1671            return Err(ParseError::new(ParseErrorKind::InvalidSize {
1672                min: MINIMUM_LEN,
1673                max: MAXIMUM_LEN,
1674                actual: length,
1675            }));
1676        }
1677
1678        Ok(Self {
1679            length,
1680            parser: Parser::new(data),
1681            _phantom: PhantomData,
1682        })
1683    }
1684
1685    pub fn len(&self) -> usize {
1686        self.length
1687    }
1688
1689    pub fn is_empty(&self) -> bool {
1690        self.len() == 0
1691    }
1692}
1693
1694impl<'a, T: Asn1Readable<'a>, const MINIMUM_LEN: usize, const MAXIMUM_LEN: usize> Clone
1695    for SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN>
1696{
1697    fn clone(&self) -> SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN> {
1698        SequenceOf {
1699            parser: self.parser.clone_internal(),
1700            length: self.length,
1701            _phantom: PhantomData,
1702        }
1703    }
1704}
1705
1706impl<'a, T: Asn1Readable<'a> + PartialEq, const MINIMUM_LEN: usize, const MAXIMUM_LEN: usize>
1707    PartialEq for SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN>
1708{
1709    fn eq(&self, other: &Self) -> bool {
1710        let mut it1 = self.clone();
1711        let mut it2 = other.clone();
1712        loop {
1713            match (it1.next(), it2.next()) {
1714                (Some(v1), Some(v2)) => {
1715                    if v1 != v2 {
1716                        return false;
1717                    }
1718                }
1719                (None, None) => return true,
1720                _ => return false,
1721            }
1722        }
1723    }
1724}
1725
1726impl<'a, T: Asn1Readable<'a> + Eq, const MINIMUM_LEN: usize, const MAXIMUM_LEN: usize> Eq
1727    for SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN>
1728{
1729}
1730
1731impl<'a, T: Asn1Readable<'a> + Hash, const MINIMUM_LEN: usize, const MAXIMUM_LEN: usize> Hash
1732    for SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN>
1733{
1734    fn hash<H: Hasher>(&self, state: &mut H) {
1735        for val in self.clone() {
1736            val.hash(state);
1737        }
1738    }
1739}
1740
1741impl<'a, T: Asn1Readable<'a> + 'a, const MINIMUM_LEN: usize, const MAXIMUM_LEN: usize>
1742    SimpleAsn1Readable<'a> for SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN>
1743{
1744    const TAG: Tag = Tag::constructed(0x10);
1745    #[inline]
1746    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
1747        SequenceOf::new(data)
1748    }
1749}
1750
1751impl<'a, T: Asn1Readable<'a>, const MINIMUM_LEN: usize, const MAXIMUM_LEN: usize> Iterator
1752    for SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN>
1753{
1754    type Item = T;
1755
1756    fn next(&mut self) -> Option<Self::Item> {
1757        if self.parser.is_empty() {
1758            return None;
1759        }
1760        self.length -= 1;
1761        Some(
1762            self.parser
1763                .read_element::<T>()
1764                .expect("Should always succeed"),
1765        )
1766    }
1767}
1768
1769impl<
1770        'a,
1771        T: Asn1Readable<'a> + Asn1Writable,
1772        const MINIMUM_LEN: usize,
1773        const MAXIMUM_LEN: usize,
1774    > SimpleAsn1Writable for SequenceOf<'a, T, MINIMUM_LEN, MAXIMUM_LEN>
1775{
1776    const TAG: Tag = Tag::constructed(0x10);
1777    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1778        let mut w = Writer::new(dest);
1779        for el in self.clone() {
1780            w.write_element(&el)?;
1781        }
1782
1783        Ok(())
1784    }
1785
1786    fn data_length(&self) -> Option<usize> {
1787        let iter = self.clone();
1788        iter.map(|el| el.encoded_length()).sum()
1789    }
1790}
1791
1792/// Writes a `SEQUENCE OF` ASN.1 structure from a slice of `T`.
1793#[derive(Hash, PartialEq, Eq, Clone)]
1794pub struct SequenceOfWriter<'a, T, V: Borrow<[T]> = &'a [T]> {
1795    vals: V,
1796    _phantom: PhantomData<&'a T>,
1797}
1798
1799impl<T, V: Borrow<[T]>> SequenceOfWriter<'_, T, V> {
1800    pub fn new(vals: V) -> Self {
1801        SequenceOfWriter {
1802            vals,
1803            _phantom: PhantomData,
1804        }
1805    }
1806}
1807
1808impl<T: Asn1Writable, V: Borrow<[T]>> SimpleAsn1Writable for SequenceOfWriter<'_, T, V> {
1809    const TAG: Tag = Tag::constructed(0x10);
1810    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1811        let mut w = Writer::new(dest);
1812        for el in self.vals.borrow() {
1813            w.write_element(el)?;
1814        }
1815
1816        Ok(())
1817    }
1818
1819    fn data_length(&self) -> Option<usize> {
1820        let vals = self.vals.borrow();
1821        vals.iter().map(|v| v.encoded_length()).sum()
1822    }
1823}
1824
1825/// Represents an ASN.1 `SET OF`. This is an `Iterator` over values that
1826/// are decoded.
1827pub struct SetOf<'a, T> {
1828    parser: Parser<'a>,
1829    _phantom: PhantomData<T>,
1830}
1831
1832impl<'a, T: Asn1Readable<'a>> SetOf<'a, T> {
1833    #[inline]
1834    pub(crate) fn new(data: &'a [u8]) -> SetOf<'a, T> {
1835        SetOf {
1836            parser: Parser::new(data),
1837            _phantom: PhantomData,
1838        }
1839    }
1840}
1841
1842impl<'a, T: Asn1Readable<'a>> Clone for SetOf<'a, T> {
1843    fn clone(&self) -> SetOf<'a, T> {
1844        SetOf {
1845            parser: self.parser.clone_internal(),
1846            _phantom: PhantomData,
1847        }
1848    }
1849}
1850
1851impl<'a, T: Asn1Readable<'a> + PartialEq> PartialEq for SetOf<'a, T> {
1852    fn eq(&self, other: &Self) -> bool {
1853        let mut it1 = self.clone();
1854        let mut it2 = other.clone();
1855        loop {
1856            match (it1.next(), it2.next()) {
1857                (Some(v1), Some(v2)) => {
1858                    if v1 != v2 {
1859                        return false;
1860                    }
1861                }
1862                (None, None) => return true,
1863                _ => return false,
1864            }
1865        }
1866    }
1867}
1868
1869impl<'a, T: Asn1Readable<'a> + Eq> Eq for SetOf<'a, T> {}
1870
1871impl<'a, T: Asn1Readable<'a> + Hash> Hash for SetOf<'a, T> {
1872    fn hash<H: Hasher>(&self, state: &mut H) {
1873        for val in self.clone() {
1874            val.hash(state);
1875        }
1876    }
1877}
1878
1879impl<'a, T: Asn1Readable<'a> + 'a> SimpleAsn1Readable<'a> for SetOf<'a, T> {
1880    const TAG: Tag = Tag::constructed(0x11);
1881
1882    #[inline]
1883    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
1884        parse(data, |p| {
1885            let mut last_element: Option<Tlv<'a>> = None;
1886            let mut i = 0;
1887            while !p.is_empty() {
1888                let el = p
1889                    .read_tlv()
1890                    .map_err(|e| e.add_location(ParseLocation::Index(i)))?;
1891                if let Some(last_el) = last_element {
1892                    if el.full_data < last_el.full_data {
1893                        return Err(ParseError::new(ParseErrorKind::InvalidSetOrdering)
1894                            .add_location(ParseLocation::Index(i)));
1895                    }
1896                }
1897                last_element = Some(el);
1898                el.parse::<T>()
1899                    .map_err(|e| e.add_location(ParseLocation::Index(i)))?;
1900                i += 1;
1901            }
1902            Ok(())
1903        })?;
1904        Ok(SetOf::new(data))
1905    }
1906}
1907
1908impl<'a, T: Asn1Readable<'a>> Iterator for SetOf<'a, T> {
1909    type Item = T;
1910
1911    fn next(&mut self) -> Option<Self::Item> {
1912        if self.parser.is_empty() {
1913            return None;
1914        }
1915        Some(
1916            self.parser
1917                .read_element::<T>()
1918                .expect("Should always succeed"),
1919        )
1920    }
1921}
1922
1923impl<'a, T: Asn1Readable<'a> + Asn1Writable> SimpleAsn1Writable for SetOf<'a, T> {
1924    const TAG: Tag = Tag::constructed(0x11);
1925    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1926        let mut w = Writer::new(dest);
1927        // We are known to be ordered correctly because that's an invariant for
1928        // `self`, so we don't need to sort here.
1929        for el in self.clone() {
1930            w.write_element(&el)?;
1931        }
1932
1933        Ok(())
1934    }
1935    fn data_length(&self) -> Option<usize> {
1936        let iter = self.clone();
1937        iter.map(|el| el.encoded_length()).sum()
1938    }
1939}
1940
1941/// Writes an ASN.1 `SET OF` whose contents is a slice of `T`. This type handles
1942/// ensuring that the values are properly ordered when written as DER.
1943#[derive(Hash, PartialEq, Eq, Clone)]
1944pub struct SetOfWriter<'a, T, V: Borrow<[T]> = &'a [T]> {
1945    vals: V,
1946    _phantom: PhantomData<&'a T>,
1947}
1948
1949impl<T: Asn1Writable, V: Borrow<[T]>> SetOfWriter<'_, T, V> {
1950    pub fn new(vals: V) -> Self {
1951        SetOfWriter {
1952            vals,
1953            _phantom: PhantomData,
1954        }
1955    }
1956}
1957
1958impl<T: Asn1Writable, V: Borrow<[T]>> SimpleAsn1Writable for SetOfWriter<'_, T, V> {
1959    const TAG: Tag = Tag::constructed(0x11);
1960    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
1961        let vals = self.vals.borrow();
1962        if vals.is_empty() {
1963            return Ok(());
1964        } else if vals.len() == 1 {
1965            let mut w = Writer::new(dest);
1966            w.write_element(&vals[0])?;
1967            return Ok(());
1968        }
1969
1970        // Optimization: use the dest storage as scratch, then truncate.
1971        let mut data = WriteBuf::new(vec![]);
1972        let mut w = Writer::new(&mut data);
1973        // Optimization opportunity: use a SmallVec here.
1974        let mut spans = vec![];
1975
1976        let mut pos = 0;
1977        for el in vals {
1978            w.write_element(el)?;
1979            let l = w.buf.len();
1980            spans.push(pos..l);
1981            pos = l;
1982        }
1983        let data = data.as_slice();
1984        spans.sort_by_key(|v| &data[v.clone()]);
1985        for span in spans {
1986            dest.push_slice(&data[span])?;
1987        }
1988
1989        Ok(())
1990    }
1991
1992    fn data_length(&self) -> Option<usize> {
1993        let vals = self.vals.borrow();
1994        vals.iter().map(|v| v.encoded_length()).sum()
1995    }
1996}
1997
1998/// `Implicit` is a type which wraps another ASN.1 type, indicating that the tag is an ASN.1
1999/// `IMPLICIT`. This will generally be used with `Option` or `Choice`.
2000#[derive(PartialEq, Eq, Debug)]
2001pub struct Implicit<T, const TAG: u32> {
2002    inner: T,
2003}
2004
2005impl<T, const TAG: u32> Implicit<T, { TAG }> {
2006    pub fn new(v: T) -> Self {
2007        Implicit { inner: v }
2008    }
2009
2010    pub fn as_inner(&self) -> &T {
2011        &self.inner
2012    }
2013
2014    pub fn into_inner(self) -> T {
2015        self.inner
2016    }
2017}
2018
2019impl<T, const TAG: u32> From<T> for Implicit<T, { TAG }> {
2020    fn from(v: T) -> Self {
2021        Implicit::new(v)
2022    }
2023}
2024
2025impl<'a, T: SimpleAsn1Readable<'a>, const TAG: u32> SimpleAsn1Readable<'a>
2026    for Implicit<T, { TAG }>
2027{
2028    const TAG: Tag = crate::implicit_tag(TAG, T::TAG);
2029    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
2030        Ok(Implicit::new(T::parse_data(data)?))
2031    }
2032}
2033
2034impl<T: SimpleAsn1Writable, const TAG: u32> SimpleAsn1Writable for Implicit<T, { TAG }> {
2035    const TAG: Tag = crate::implicit_tag(TAG, T::TAG);
2036
2037    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
2038        self.inner.write_data(dest)
2039    }
2040
2041    fn data_length(&self) -> Option<usize> {
2042        self.inner.data_length()
2043    }
2044}
2045
2046/// `Explicit` is a type which wraps another ASN.1 type, indicating that the tag is an ASN.1
2047/// `EXPLICIT`. This will generally be used with `Option` or `Choice`.
2048#[derive(PartialEq, Eq, Debug)]
2049pub struct Explicit<T, const TAG: u32> {
2050    inner: T,
2051}
2052
2053impl<T, const TAG: u32> Explicit<T, { TAG }> {
2054    pub fn new(v: T) -> Self {
2055        Explicit { inner: v }
2056    }
2057
2058    pub fn as_inner(&self) -> &T {
2059        &self.inner
2060    }
2061
2062    pub fn into_inner(self) -> T {
2063        self.inner
2064    }
2065}
2066
2067impl<T, const TAG: u32> From<T> for Explicit<T, { TAG }> {
2068    fn from(v: T) -> Self {
2069        Explicit::new(v)
2070    }
2071}
2072
2073impl<'a, T: Asn1Readable<'a>, const TAG: u32> SimpleAsn1Readable<'a> for Explicit<T, { TAG }> {
2074    const TAG: Tag = crate::explicit_tag(TAG);
2075    fn parse_data(data: &'a [u8]) -> ParseResult<Self> {
2076        Ok(Explicit::new(parse(data, Parser::read_element::<T>)?))
2077    }
2078}
2079
2080impl<T: Asn1Writable, const TAG: u32> SimpleAsn1Writable for Explicit<T, { TAG }> {
2081    const TAG: Tag = crate::explicit_tag(TAG);
2082    fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
2083        Writer::new(dest).write_element(&self.inner)
2084    }
2085    fn data_length(&self) -> Option<usize> {
2086        self.inner.encoded_length()
2087    }
2088}
2089
2090impl<'a, T: Asn1Readable<'a>, U: Asn1DefinedByReadable<'a, T>, const TAG: u32>
2091    Asn1DefinedByReadable<'a, T> for Explicit<U, { TAG }>
2092{
2093    fn parse(item: T, parser: &mut Parser<'a>) -> ParseResult<Self> {
2094        let tlv = parser.read_element::<Explicit<Tlv<'_>, TAG>>()?;
2095        Ok(Explicit::new(parse(tlv.as_inner().full_data(), |p| {
2096            U::parse(item, p)
2097        })?))
2098    }
2099}
2100
2101impl<T: Asn1Writable, U: Asn1DefinedByWritable<T>, const TAG: u32> Asn1DefinedByWritable<T>
2102    for Explicit<U, { TAG }>
2103{
2104    fn item(&self) -> &T {
2105        self.as_inner().item()
2106    }
2107    fn write(&self, dest: &mut Writer<'_>) -> WriteResult {
2108        dest.write_tlv(
2109            crate::explicit_tag(TAG),
2110            self.as_inner().encoded_length(),
2111            |dest| self.as_inner().write(&mut Writer::new(dest)),
2112        )
2113    }
2114    fn encoded_length(&self) -> Option<usize> {
2115        let inner_len = self.as_inner().encoded_length()?;
2116        Some(Tlv::full_length(crate::explicit_tag(TAG), inner_len))
2117    }
2118}
2119
2120#[derive(PartialEq, Eq, Debug, Clone, Hash)]
2121pub struct DefinedByMarker<T>(core::marker::PhantomData<T>);
2122
2123impl<T> DefinedByMarker<T> {
2124    pub const fn marker() -> DefinedByMarker<T> {
2125        DefinedByMarker(core::marker::PhantomData)
2126    }
2127}
2128
2129impl<'a, T: Asn1Readable<'a>> Asn1Readable<'a> for DefinedByMarker<T> {
2130    fn parse(_: &mut Parser<'a>) -> ParseResult<Self> {
2131        panic!("parse() should never be called on a DefinedByMarker")
2132    }
2133    fn can_parse(_: Tag) -> bool {
2134        panic!("can_parse() should never be called on a DefinedByMarker")
2135    }
2136}
2137
2138impl<T: Asn1Writable> Asn1Writable for DefinedByMarker<T> {
2139    fn write(&self, _: &mut Writer<'_>) -> WriteResult {
2140        panic!("write() should never be called on a DefinedByMarker")
2141    }
2142
2143    fn encoded_length(&self) -> Option<usize> {
2144        panic!("encoded_length() should never be called on a DefinedByMarker")
2145    }
2146}
2147
2148#[cfg(test)]
2149mod tests {
2150    use crate::{
2151        parse_single, Asn1Readable, Asn1Writable, BigInt, BigUint, DateTime, DefinedByMarker,
2152        Enumerated, GeneralizedTime, IA5String, ObjectIdentifier, OctetStringEncoded, OwnedBigInt,
2153        OwnedBigUint, ParseError, ParseErrorKind, PrintableString, SequenceOf, SequenceOfWriter,
2154        SetOf, SetOfWriter, Tag, Tlv, UtcTime, Utf8String, VisibleString, X509GeneralizedTime,
2155    };
2156    use crate::{Explicit, Implicit};
2157    #[cfg(not(feature = "std"))]
2158    use alloc::vec;
2159    #[cfg(not(feature = "std"))]
2160    use alloc::vec::Vec;
2161    #[cfg(feature = "std")]
2162    use core::hash::{Hash, Hasher};
2163    #[cfg(feature = "std")]
2164    use std::collections::hash_map::DefaultHasher;
2165
2166    #[test]
2167    fn test_octet_string_encoded() {
2168        assert_eq!(OctetStringEncoded::new(12).get(), &12);
2169        assert_eq!(OctetStringEncoded::new(12).into_inner(), 12);
2170    }
2171
2172    #[test]
2173    fn test_printable_string_new() {
2174        assert!(PrintableString::new("abc").is_some());
2175        assert!(PrintableString::new("").is_some());
2176        assert!(PrintableString::new(" ").is_some());
2177        assert!(PrintableString::new("%").is_none());
2178        assert!(PrintableString::new("\x00").is_none());
2179    }
2180
2181    #[test]
2182    fn test_printable_string_as_str() {
2183        assert_eq!(PrintableString::new("abc").unwrap().as_str(), "abc");
2184    }
2185
2186    #[test]
2187    fn test_ia5string_new() {
2188        assert!(IA5String::new("abc").is_some());
2189        assert!(IA5String::new("").is_some());
2190        assert!(IA5String::new(" ").is_some());
2191        assert!(IA5String::new("%").is_some());
2192        assert!(IA5String::new("😄").is_none());
2193    }
2194
2195    #[test]
2196    fn test_ia5string_as_str() {
2197        assert_eq!(IA5String::new("abc").unwrap().as_str(), "abc");
2198    }
2199
2200    #[test]
2201    fn test_utf8string_as_str() {
2202        assert_eq!(Utf8String::new("abc").as_str(), "abc");
2203    }
2204
2205    #[test]
2206    fn test_visiblestring_new() {
2207        assert!(VisibleString::new("").is_some());
2208        assert!(VisibleString::new("abc").is_some());
2209        assert!(VisibleString::new("\n").is_none());
2210    }
2211
2212    #[test]
2213    fn test_visiblestring_as_str() {
2214        assert_eq!(VisibleString::new("abc").unwrap().as_str(), "abc");
2215    }
2216
2217    #[test]
2218    fn test_tlv_data() {
2219        let tlv = parse_single::<Tlv<'_>>(b"\x01\x03abc").unwrap();
2220        assert_eq!(tlv.data(), b"abc");
2221    }
2222
2223    #[test]
2224    fn test_tlv_full_data() {
2225        let tlv = parse_single::<Tlv<'_>>(b"\x01\x03abc").unwrap();
2226        assert_eq!(tlv.full_data(), b"\x01\x03abc");
2227    }
2228
2229    #[test]
2230    fn test_tlv_parse() {
2231        let tlv = Tlv {
2232            tag: Tag::primitive(0x2),
2233            data: b"\x03",
2234            full_data: b"\x02\x01\x03",
2235        };
2236        assert_eq!(tlv.parse::<u64>(), Ok(3));
2237        assert_eq!(
2238            tlv.parse::<&[u8]>(),
2239            Err(ParseError::new(ParseErrorKind::UnexpectedTag {
2240                actual: Tag::primitive(0x2)
2241            }))
2242        );
2243    }
2244
2245    #[test]
2246    fn test_biguint_as_bytes() {
2247        assert_eq!(BigUint::new(b"\x01").unwrap().as_bytes(), b"\x01");
2248        assert_eq!(
2249            OwnedBigUint::new(b"\x01".to_vec()).unwrap().as_bytes(),
2250            b"\x01"
2251        );
2252    }
2253
2254    #[test]
2255    fn test_bigint_as_bytes() {
2256        assert_eq!(BigInt::new(b"\x01").unwrap().as_bytes(), b"\x01");
2257        assert_eq!(
2258            OwnedBigInt::new(b"\x01".to_vec()).unwrap().as_bytes(),
2259            b"\x01"
2260        );
2261    }
2262
2263    #[test]
2264    fn test_bigint_is_negative() {
2265        assert!(!BigInt::new(b"\x01").unwrap().is_negative()); // 1
2266        assert!(!BigInt::new(b"\x00").unwrap().is_negative()); // 0
2267        assert!(BigInt::new(b"\xff").unwrap().is_negative()); // -1
2268
2269        assert!(!OwnedBigInt::new(b"\x01".to_vec()).unwrap().is_negative()); // 1
2270        assert!(!OwnedBigInt::new(b"\x00".to_vec()).unwrap().is_negative()); // 0
2271        assert!(OwnedBigInt::new(b"\xff".to_vec()).unwrap().is_negative()); // -1
2272    }
2273
2274    #[test]
2275    fn test_sequence_of_clone() {
2276        let mut seq1 =
2277            parse_single::<SequenceOf<'_, u64>>(b"\x30\x09\x02\x01\x01\x02\x01\x02\x02\x01\x03")
2278                .unwrap();
2279        assert_eq!(seq1.next(), Some(1));
2280        let seq2 = seq1.clone();
2281        assert_eq!(seq1.collect::<Vec<_>>(), vec![2, 3]);
2282        assert_eq!(seq2.collect::<Vec<_>>(), vec![2, 3]);
2283    }
2284
2285    #[test]
2286    fn test_sequence_of_len() {
2287        let mut seq1 =
2288            parse_single::<SequenceOf<'_, u64>>(b"\x30\x09\x02\x01\x01\x02\x01\x02\x02\x01\x03")
2289                .unwrap();
2290        let seq2 = seq1.clone();
2291
2292        assert_eq!(seq1.len(), 3);
2293        assert!(seq1.next().is_some());
2294        assert_eq!(seq1.len(), 2);
2295        assert_eq!(seq2.len(), 3);
2296        assert!(seq1.next().is_some());
2297        assert!(seq1.next().is_some());
2298        assert_eq!(seq1.len(), 0);
2299        assert!(seq1.next().is_none());
2300        assert_eq!(seq1.len(), 0);
2301        assert!(seq1.is_empty());
2302        assert_eq!(seq2.len(), 3);
2303        assert!(!seq2.is_empty());
2304    }
2305
2306    #[cfg(feature = "std")]
2307    fn hash<T: Hash>(v: &T) -> u64 {
2308        let mut h = DefaultHasher::new();
2309        v.hash(&mut h);
2310        h.finish()
2311    }
2312
2313    #[test]
2314    fn test_set_of_eq() {
2315        let s1 = SetOf::<bool>::new(b"");
2316        let s2 = SetOf::<bool>::new(b"");
2317        let s3 = SetOf::<bool>::new(b"\x01\x01\x00");
2318        let s4 = SetOf::<bool>::new(b"\x01\x01\xff");
2319
2320        assert!(s1 == s2);
2321
2322        assert!(s2 != s3);
2323
2324        assert!(s3 == s3);
2325
2326        assert!(s3 != s4);
2327    }
2328
2329    #[cfg(feature = "std")]
2330    #[test]
2331    fn test_set_of_hash() {
2332        let s1 = SetOf::<bool>::new(b"");
2333        let s2 = SetOf::<bool>::new(b"");
2334        let s3 = SetOf::<bool>::new(b"\x01\x01\x00");
2335        let s4 = SetOf::<bool>::new(b"\x01\x01\xff");
2336
2337        assert_eq!(hash(&s1), hash(&s2));
2338
2339        assert_ne!(hash(&s2), hash(&s3));
2340
2341        assert_ne!(hash(&s3), hash(&s4));
2342    }
2343
2344    #[test]
2345    fn test_sequence_of_eq() {
2346        let s1 = SequenceOf::<bool>::new(b"").unwrap();
2347        let s2 = SequenceOf::<bool>::new(b"").unwrap();
2348        let s3 = SequenceOf::<bool>::new(b"\x01\x01\x00").unwrap();
2349        let s4 = SequenceOf::<bool>::new(b"\x01\x01\xff").unwrap();
2350
2351        assert!(s1 == s2);
2352
2353        assert!(s2 != s3);
2354
2355        assert!(s3 == s3);
2356
2357        assert!(s3 != s4);
2358    }
2359
2360    #[cfg(feature = "std")]
2361    #[test]
2362    fn test_sequence_of_hash() {
2363        let s1 = SequenceOf::<bool>::new(b"").unwrap();
2364        let s2 = SequenceOf::<bool>::new(b"").unwrap();
2365        let s3 = SequenceOf::<bool>::new(b"\x01\x01\x00").unwrap();
2366        let s4 = SequenceOf::<bool>::new(b"\x01\x01\xff").unwrap();
2367
2368        assert_eq!(hash(&s1), hash(&s2));
2369
2370        assert_ne!(hash(&s2), hash(&s3));
2371
2372        assert_ne!(hash(&s3), hash(&s4));
2373    }
2374
2375    #[test]
2376    fn test_sequence_of_writer_clone() {
2377        let s1 = SequenceOfWriter::new([1, 2, 3]);
2378        let s2 = s1.clone();
2379
2380        assert!(s1 == s2);
2381    }
2382
2383    #[test]
2384    fn test_set_of_writer_clone() {
2385        let s1 = SetOfWriter::new([1, 2, 3]);
2386        let s2 = s1.clone();
2387
2388        assert!(s1 == s2);
2389    }
2390
2391    #[test]
2392    fn test_datetime_new() {
2393        assert!(DateTime::new(2038, 13, 1, 12, 0, 0).is_err());
2394        assert!(DateTime::new(2000, 1, 1, 12, 60, 0).is_err());
2395        assert!(DateTime::new(2000, 1, 1, 12, 0, 60).is_err());
2396        assert!(DateTime::new(2000, 1, 1, 24, 0, 0).is_err());
2397    }
2398
2399    #[test]
2400    fn test_datetime_partialord() {
2401        let point = DateTime::new(2023, 6, 15, 14, 26, 5).unwrap();
2402
2403        assert!(point < DateTime::new(2023, 6, 15, 14, 26, 6).unwrap());
2404        assert!(point < DateTime::new(2023, 6, 15, 14, 27, 5).unwrap());
2405        assert!(point < DateTime::new(2023, 6, 15, 15, 26, 5).unwrap());
2406        assert!(point < DateTime::new(2023, 6, 16, 14, 26, 5).unwrap());
2407        assert!(point < DateTime::new(2023, 7, 15, 14, 26, 5).unwrap());
2408        assert!(point < DateTime::new(2024, 6, 15, 14, 26, 5).unwrap());
2409
2410        assert!(point > DateTime::new(2023, 6, 15, 14, 26, 4).unwrap());
2411        assert!(point > DateTime::new(2023, 6, 15, 14, 25, 5).unwrap());
2412        assert!(point > DateTime::new(2023, 6, 15, 13, 26, 5).unwrap());
2413        assert!(point > DateTime::new(2023, 6, 14, 14, 26, 5).unwrap());
2414        assert!(point > DateTime::new(2023, 5, 15, 14, 26, 5).unwrap());
2415        assert!(point > DateTime::new(2022, 6, 15, 14, 26, 5).unwrap());
2416    }
2417
2418    #[test]
2419    fn test_utctime_new() {
2420        assert!(UtcTime::new(DateTime::new(1950, 1, 1, 12, 0, 0).unwrap()).is_ok());
2421        assert!(UtcTime::new(DateTime::new(1949, 1, 1, 12, 0, 0).unwrap()).is_err());
2422        assert!(UtcTime::new(DateTime::new(2050, 1, 1, 12, 0, 0).unwrap()).is_err());
2423        assert!(UtcTime::new(DateTime::new(2100, 1, 1, 12, 0, 0).unwrap()).is_err());
2424    }
2425
2426    #[test]
2427    fn test_x509_generalizedtime_new() {
2428        assert!(X509GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap()).is_ok());
2429    }
2430
2431    #[test]
2432    fn test_generalized_time_new() {
2433        assert!(
2434            GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), Some(1234))
2435                .is_ok()
2436        );
2437        assert!(
2438            GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), None).is_ok()
2439        );
2440        // Maximum fractional time is 999,999,999 nanos.
2441        assert!(GeneralizedTime::new(
2442            DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(),
2443            Some(999_999_999_u32)
2444        )
2445        .is_ok());
2446        assert!(GeneralizedTime::new(
2447            DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(),
2448            Some(1e9 as u32)
2449        )
2450        .is_err());
2451        assert!(GeneralizedTime::new(
2452            DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(),
2453            Some(1e9 as u32 + 1)
2454        )
2455        .is_err());
2456    }
2457
2458    #[test]
2459    fn test_generalized_time_partial_ord() {
2460        let point =
2461            GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), Some(1234))
2462                .unwrap();
2463        assert!(
2464            point
2465                < GeneralizedTime::new(DateTime::new(2023, 6, 30, 23, 59, 59).unwrap(), Some(1234))
2466                    .unwrap()
2467        );
2468        assert!(
2469            point
2470                < GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), Some(1235))
2471                    .unwrap()
2472        );
2473        assert!(
2474            point
2475                > GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), None)
2476                    .unwrap()
2477        );
2478    }
2479
2480    #[test]
2481    fn test_enumerated_value() {
2482        assert_eq!(Enumerated::new(4).value(), 4);
2483    }
2484
2485    #[test]
2486    fn test_implicit_as_inner() {
2487        assert_eq!(Implicit::<i32, 0>::new(12).as_inner(), &12);
2488    }
2489
2490    #[test]
2491    fn test_explicit_as_inner() {
2492        assert_eq!(Explicit::<i32, 0>::new(12).as_inner(), &12);
2493    }
2494
2495    #[test]
2496    fn test_const() {
2497        const _: DefinedByMarker<ObjectIdentifier> = DefinedByMarker::marker();
2498    }
2499
2500    #[test]
2501    #[should_panic]
2502    fn test_defined_by_marker_parse() {
2503        crate::parse(b"", DefinedByMarker::<ObjectIdentifier>::parse).unwrap();
2504    }
2505
2506    #[test]
2507    #[should_panic]
2508    fn test_defined_by_marker_can_parse() {
2509        DefinedByMarker::<ObjectIdentifier>::can_parse(Tag::primitive(2));
2510    }
2511
2512    #[test]
2513    #[should_panic]
2514    fn test_defined_by_marker_write() {
2515        crate::write(|w| DefinedByMarker::<ObjectIdentifier>::marker().write(w)).unwrap();
2516    }
2517
2518    #[test]
2519    #[should_panic]
2520    fn test_defined_by_marker_encoded_length() {
2521        DefinedByMarker::<ObjectIdentifier>::marker().encoded_length();
2522    }
2523}