Skip to main content

der/asn1/
sequence.rs

1//! The [`Sequence`] trait simplifies writing decoders/encoders which map ASN.1
2//! `SEQUENCE`s to Rust structs.
3
4use crate::{
5    BytesRef, DecodeValue, EncodeValue, Error, ErrorKind, FixedTag, Header, Length, Reader, Result,
6    Tag, Writer,
7};
8
9#[cfg(feature = "alloc")]
10use alloc::boxed::Box;
11
12/// Marker trait for ASN.1 `SEQUENCE`s.
13///
14/// This is mainly used for custom derive.
15pub trait Sequence<'a> {}
16
17impl<'a, S> FixedTag for S
18where
19    S: Sequence<'a>,
20{
21    const TAG: Tag = Tag::Sequence;
22}
23
24#[cfg(feature = "alloc")]
25impl<'a, T> Sequence<'a> for Box<T> where T: Sequence<'a> {}
26
27/// The [`SequenceRef`] type provides raw access to the octets which comprise a
28/// DER-encoded `SEQUENCE`.
29///
30/// This is a zero-copy reference type which borrows from the input data.
31#[derive(Debug, Eq, PartialEq, PartialOrd, Ord)]
32#[repr(transparent)]
33pub struct SequenceRef {
34    /// Body of the `SEQUENCE`.
35    body: BytesRef,
36}
37
38impl SequenceRef {
39    /// Create a new ASN.1 `SEQUENCE` from a byte slice.
40    ///
41    /// # Errors
42    /// Returns [`Error`] in the event `slice` is too long.
43    pub fn new(slice: &[u8]) -> Result<&Self> {
44        BytesRef::new(slice)
45            .map(Self::from_bytes_ref)
46            .map_err(|_| ErrorKind::Length { tag: Tag::Sequence }.into())
47    }
48
49    /// Create a [`SequenceRef`] from a [`BytesRef`].
50    ///
51    /// Implemented as an inherent method to keep [`BytesRef`] out of the public API.
52    fn from_bytes_ref(bytes_ref: &BytesRef) -> &Self {
53        // SAFETY: `Self` is a `repr(transparent)` newtype for `BytesRef`
54        #[allow(unsafe_code)]
55        unsafe {
56            &*(bytes_ref.as_ptr() as *const Self)
57        }
58    }
59
60    /// Borrow the inner byte slice.
61    #[must_use]
62    pub fn as_bytes(&self) -> &[u8] {
63        self.body.as_slice()
64    }
65}
66
67impl AsRef<[u8]> for SequenceRef {
68    fn as_ref(&self) -> &[u8] {
69        self.as_bytes()
70    }
71}
72
73impl<'a> DecodeValue<'a> for &'a SequenceRef {
74    type Error = Error;
75
76    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self> {
77        <&'a BytesRef>::decode_value(reader, header).map(SequenceRef::from_bytes_ref)
78    }
79}
80
81impl EncodeValue for SequenceRef {
82    fn value_len(&self) -> Result<Length> {
83        Ok(self.body.len())
84    }
85
86    fn encode_value(&self, writer: &mut impl Writer) -> Result<()> {
87        self.body.encode_value(writer)
88    }
89}
90
91impl<'a> Sequence<'a> for &'a SequenceRef {}