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
use crate::{
asn1::Any, Choice, Decodable, Encodable, Encoder, Error, Header, Length, Result, Tag, TagNumber,
};
use core::convert::TryFrom;
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct ContextSpecific<'a> {
pub tag_number: TagNumber,
pub value: Any<'a>,
}
impl<'a> Choice<'a> for ContextSpecific<'a> {
fn can_decode(tag: Tag) -> bool {
matches!(tag, Tag::ContextSpecific(_))
}
}
impl<'a> Encodable for ContextSpecific<'a> {
fn encoded_len(&self) -> Result<Length> {
self.value.encoded_len()?.for_tlv()
}
fn encode(&self, encoder: &mut Encoder<'_>) -> Result<()> {
let tag = Tag::ContextSpecific(self.tag_number);
Header::new(tag, self.value.encoded_len()?)?.encode(encoder)?;
self.value.encode(encoder)
}
}
impl<'a> From<&ContextSpecific<'a>> for ContextSpecific<'a> {
fn from(value: &ContextSpecific<'a>) -> ContextSpecific<'a> {
*value
}
}
impl<'a> TryFrom<Any<'a>> for ContextSpecific<'a> {
type Error = Error;
fn try_from(any: Any<'a>) -> Result<ContextSpecific<'a>> {
match any.tag() {
Tag::ContextSpecific(tag_number) => Ok(Self {
tag_number,
value: Any::from_der(any.as_bytes())?,
}),
tag => Err(tag.unexpected_error(None)),
}
}
}
#[cfg(test)]
mod tests {
use super::ContextSpecific;
use crate::{Decodable, Encodable, Tag};
use hex_literal::hex;
const EXAMPLE_BYTES: &[u8] =
&hex!("A123032100A3A7EAE3A8373830BC47E1167BC50E1DB551999651E0E2DC587623438EAC3F31");
#[test]
fn round_trip() {
let field = ContextSpecific::from_der(EXAMPLE_BYTES).unwrap();
assert_eq!(field.tag_number.value(), 1);
assert_eq!(field.value.tag(), Tag::BitString);
assert_eq!(field.value.as_bytes(), &EXAMPLE_BYTES[5..]);
let mut buf = [0u8; 128];
let encoded = field.encode_to_slice(&mut buf).unwrap();
assert_eq!(encoded, EXAMPLE_BYTES);
}
}