simple_tlv/
tag.rs

1use core::{convert::TryFrom, fmt};
2use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, TaggedValue};
3
4/// The tag field consists of a single byte encoding a tag number from 1 to 254. The values '00' and 'FF' are invalid.
5#[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    /// Assert that this [`Tag`] matches the provided expected tag.
20    ///
21    /// On mismatch, returns an [`Error`] with [`ErrorKind::UnexpectedTag`].
22    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    // fn tagged(&self, tag: Tag) -> TaggedValue<&Self> {
38    //     TaggedValue::new(tag, self)
39    // }
40}
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        // f.write_str(self.type_name())
61        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}