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
use core::{convert::TryFrom, fmt};
use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, TaggedValue};
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Tag(u8);
impl TryFrom<u8> for Tag {
type Error = Error;
fn try_from(tag_number: u8) -> Result<Self> {
match tag_number {
byte if byte == 0 || byte == 0xFF => Err(ErrorKind::InvalidTag { byte }.into()),
valid_tag_number => Ok(Self(valid_tag_number)),
}
}
}
impl Tag {
pub fn assert_eq(self, expected: Tag) -> Result<Tag> {
if self == expected {
Ok(self)
} else {
Err(ErrorKind::UnexpectedTag {
expected: Some(expected),
actual: self,
}
.into())
}
}
pub fn with_value<V>(self, value: V) -> TaggedValue<V> {
TaggedValue::new(self, value)
}
}
impl Decodable<'_> for Tag {
fn decode(decoder: &mut Decoder<'_>) -> Result<Self> {
decoder.byte().and_then(Self::try_from)
}
}
impl Encodable for Tag {
fn encoded_length(&self) -> Result<Length> {
Ok(1u8.into())
}
fn encode(&self, encoder: &mut Encoder<'_>) -> Result<()> {
encoder.byte(self.0)
}
}
impl fmt::Display for Tag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Tag('{:02x}')", self.0)
}
}
impl fmt::Debug for Tag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Tag('{:02x}')", self.0)
}
}