der/asn1/
octet_string.rs
1use crate::{
4 asn1::Any, ByteSlice, DecodeValue, Decoder, EncodeValue, Encoder, Error, ErrorKind, FixedTag,
5 Length, OrdIsValueOrd, Result, Tag,
6};
7
8#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
10pub struct OctetString<'a> {
11 inner: ByteSlice<'a>,
13}
14
15impl<'a> OctetString<'a> {
16 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 pub fn as_bytes(&self) -> &'a [u8] {
25 self.inner.as_bytes()
26 }
27
28 pub fn len(&self) -> Length {
30 self.inner.len()
31 }
32
33 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}