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