der/asn1/
octet_string.rs

1//! ASN.1 `OCTET STRING` support.
2
3use crate::{
4    asn1::Any, ByteSlice, DecodeValue, Decoder, EncodeValue, Encoder, Error, ErrorKind, FixedTag,
5    Length, OrdIsValueOrd, Result, Tag,
6};
7
8/// ASN.1 `OCTET STRING` type.
9#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
10pub struct OctetString<'a> {
11    /// Inner value
12    inner: ByteSlice<'a>,
13}
14
15impl<'a> OctetString<'a> {
16    /// Create a new ASN.1 `OCTET STRING` from a byte slice.
17    pub fn new(slice: &'a [u8]) -> Result<Self> {
18        ByteSlice::new(slice)
19            .map(|inner| Self { inner })
20            .map_err(|_| ErrorKind::Length { tag: Self::TAG }.into())
21    }
22
23    /// Borrow the inner byte slice.
24    pub fn as_bytes(&self) -> &'a [u8] {
25        self.inner.as_bytes()
26    }
27
28    /// Get the length of the inner byte slice.
29    pub fn len(&self) -> Length {
30        self.inner.len()
31    }
32
33    /// Is the inner byte slice empty?
34    pub fn is_empty(&self) -> bool {
35        self.inner.is_empty()
36    }
37}
38
39impl AsRef<[u8]> for OctetString<'_> {
40    fn as_ref(&self) -> &[u8] {
41        self.as_bytes()
42    }
43}
44
45impl<'a> DecodeValue<'a> for OctetString<'a> {
46    fn decode_value(decoder: &mut Decoder<'a>, length: Length) -> Result<Self> {
47        Ok(Self {
48            inner: ByteSlice::decode_value(decoder, length)?,
49        })
50    }
51}
52
53impl EncodeValue for OctetString<'_> {
54    fn value_len(&self) -> Result<Length> {
55        self.inner.value_len()
56    }
57
58    fn encode_value(&self, encoder: &mut Encoder<'_>) -> Result<()> {
59        self.inner.encode_value(encoder)
60    }
61}
62
63impl FixedTag for OctetString<'_> {
64    const TAG: Tag = Tag::OctetString;
65}
66
67impl OrdIsValueOrd for OctetString<'_> {}
68
69impl<'a> From<&OctetString<'a>> for OctetString<'a> {
70    fn from(value: &OctetString<'a>) -> OctetString<'a> {
71        *value
72    }
73}
74
75impl<'a> TryFrom<Any<'a>> for OctetString<'a> {
76    type Error = Error;
77
78    fn try_from(any: Any<'a>) -> Result<OctetString<'a>> {
79        any.decode_into()
80    }
81}
82
83impl<'a> From<OctetString<'a>> for Any<'a> {
84    fn from(octet_string: OctetString<'a>) -> Any<'a> {
85        Any::from_tag_and_value(Tag::OctetString, octet_string.inner)
86    }
87}
88
89impl<'a> From<OctetString<'a>> for &'a [u8] {
90    fn from(octet_string: OctetString<'a>) -> &'a [u8] {
91        octet_string.as_bytes()
92    }
93}