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
use crate::{
Asn1DerError, DerObject, Sink, error::ErrorChain,
typed::{ DerTypeView, DerDecodable, DerEncodable }
};
#[derive(Copy, Clone)]
pub struct OctetString<'a> {
object: DerObject<'a>
}
impl<'a> OctetString<'a> {
#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
pub fn new<S: Sink + Into<&'a[u8]>>(value: &[u8], mut sink: S) -> Result<Self, Asn1DerError> {
Self::write(value, &mut sink).propagate(e!("Failed to construct octet string"))?;
let object = DerObject::decode(sink.into())
.propagate(e!("Failed to load constructed octet string"))?;
Ok(Self{ object })
}
#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
pub fn get(&self) -> &[u8] {
self.object.value()
}
#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
pub fn write<S: Sink>(value: &[u8], sink: &mut S) -> Result<(), Asn1DerError> {
DerObject::write(Self::TAG, value.len(), &mut value.iter(), sink)
.propagate(e!("Failed to write octet string"))
}
}
impl<'a> DerTypeView<'a> for OctetString<'a> {
const TAG: u8 = b'\x04';
#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
fn object(&self) -> DerObject<'a> {
self.object
}
}
impl<'a> DerDecodable<'a> for OctetString<'a> {
#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
fn load(object: DerObject<'a>) -> Result<Self, Asn1DerError> {
match object.value() {
_ if object.tag() != Self::TAG => Err(einval!("DER object is not an octet string"))?,
_ => Ok(Self{ object })
}
}
}
impl<'a> DerEncodable for OctetString<'a> {
#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
fn encode<U: Sink>(&self, sink: &mut U) -> Result<(), Asn1DerError> {
self.object().encode(sink).propagate(e!("Failed to encode octet string"))
}
}
#[cfg(not(any(feature = "no_std", feature = "no_panic")))]
impl<'a> DerDecodable<'a> for Vec<u8> {
fn load(object: DerObject<'a>) -> Result<Self, Asn1DerError> {
let octet_string = OctetString::load(object).propagate(e!("Failed to load octet string"))?;
Ok(octet_string.get().to_vec())
}
}
#[cfg(not(any(feature = "no_std", feature = "no_panic")))]
impl DerEncodable for Vec<u8> {
fn encode<S: Sink>(&self, sink: &mut S) -> Result<(), Asn1DerError> {
OctetString::write(self, sink).propagate(e!("Failed to encode octet string"))
}
}