1use core::{convert::TryFrom, fmt};
2use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, TaggedValue};
3
4#[derive(Clone, Copy, Eq, PartialEq)]
6pub struct Tag(u8);
7
8impl TryFrom<u8> for Tag {
9 type Error = Error;
10 fn try_from(tag_number: u8) -> Result<Self> {
11 match tag_number {
12 byte if byte == 0 || byte == 0xFF => Err(ErrorKind::InvalidTag { byte }.into()),
13 valid_tag_number => Ok(Self(valid_tag_number)),
14 }
15 }
16}
17
18impl Tag {
19 pub fn assert_eq(self, expected: Tag) -> Result<Tag> {
23 if self == expected {
24 Ok(self)
25 } else {
26 Err(ErrorKind::UnexpectedTag {
27 expected: Some(expected),
28 actual: self,
29 }
30 .into())
31 }
32 }
33
34 pub fn with_value<V>(self, value: V) -> TaggedValue<V> {
35 TaggedValue::new(self, value)
36 }
37 }
41
42impl Decodable<'_> for Tag {
43 fn decode(decoder: &mut Decoder<'_>) -> Result<Self> {
44 decoder.byte().and_then(Self::try_from)
45 }
46}
47
48impl Encodable for Tag {
49 fn encoded_length(&self) -> Result<Length> {
50 Ok(1u8.into())
51 }
52
53 fn encode(&self, encoder: &mut Encoder<'_>) -> Result<()> {
54 encoder.byte(self.0)
55 }
56}
57
58impl fmt::Display for Tag {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 write!(f, "Tag('{:02x}')", self.0)
62 }
63}
64
65impl fmt::Debug for Tag {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 write!(f, "Tag('{:02x}')", self.0)
68 }
69}