1use crate::{Decode, Decoder, Encode, Error, Reader, Writer};
4use core::{fmt, str::FromStr};
5
6#[cfg(feature = "alloc")]
7use alloc::string::String;
8
9const MAX_LABEL_SIZE: usize = 64;
13
14pub trait Label: AsRef<str> + FromStr<Err = LabelError> {}
18
19impl<T: Label> Decode for T {
20 type Error = Error;
21
22 fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self, Error> {
23 let mut buf = [0u8; MAX_LABEL_SIZE];
24 Ok(reader.read_string(buf.as_mut())?.parse()?)
25 }
26}
27
28impl<T: Label> Encode for T {
29 fn encoded_len(&self) -> Result<usize, Error> {
30 self.as_ref().encoded_len()
31 }
32
33 fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
34 self.as_ref().encode(writer)
35 }
36}
37
38#[derive(Clone, Debug, Eq, PartialEq)]
40#[non_exhaustive]
41pub struct LabelError {
42 #[cfg(feature = "alloc")]
44 label: String,
45}
46
47impl LabelError {
48 #[cfg_attr(not(feature = "alloc"), allow(unused_variables))]
52 #[must_use]
53 pub fn new(label: &str) -> Self {
54 Self {
55 #[cfg(feature = "alloc")]
56 label: {
57 let mut stored = String::new();
58 if stored.try_reserve_exact(label.len()).is_ok() {
59 stored.push_str(label);
60 }
61 stored
62 },
63 }
64 }
65
66 #[inline]
68 #[must_use]
69 pub fn label(&self) -> &str {
70 #[cfg(not(feature = "alloc"))]
71 {
72 ""
73 }
74 #[cfg(feature = "alloc")]
75 {
76 &self.label
77 }
78 }
79}
80
81impl core::error::Error for LabelError {}
82
83impl fmt::Display for LabelError {
84 #[cfg(not(feature = "alloc"))]
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 f.write_str("invalid label")
87 }
88
89 #[cfg(feature = "alloc")]
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 write!(f, "invalid label: '{}'", self.label)
92 }
93}