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
//! Convenience trait for decoding/encoding string labels.

use crate::{Decode, Encode, Error, Reader, Writer};
use core::{fmt, str::FromStr};

#[cfg(feature = "alloc")]
use alloc::string::String;

/// Maximum size of any algorithm name/identifier.
const MAX_LABEL_SIZE: usize = 48;

/// Labels for e.g. cryptographic algorithms.
///
/// Receives a blanket impl of [`Decode`] and [`Encode`].
pub trait Label: AsRef<str> + FromStr<Err = LabelError> {}

impl<T: Label> Decode for T {
    type Error = Error;

    fn decode(reader: &mut impl Reader) -> Result<Self, Error> {
        let mut buf = [0u8; MAX_LABEL_SIZE];
        Ok(reader.read_string(buf.as_mut())?.parse()?)
    }
}

impl<T: Label> Encode for T {
    fn encoded_len(&self) -> Result<usize, Error> {
        self.as_ref().encoded_len()
    }

    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
        self.as_ref().encode(writer)
    }
}

/// Errors related to labels.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct LabelError {
    /// The label that was considered invalid.
    #[cfg(feature = "alloc")]
    label: String,
}

impl LabelError {
    /// Create a new [`LabelError`] for the given invalid label.
    #[cfg_attr(not(feature = "alloc"), allow(unused_variables))]
    pub fn new(label: &str) -> Self {
        Self {
            #[cfg(feature = "alloc")]
            label: label.into(),
        }
    }

    /// The invalid label string (if available).
    #[inline]
    pub fn label(&self) -> &str {
        #[cfg(not(feature = "alloc"))]
        {
            ""
        }
        #[cfg(feature = "alloc")]
        {
            &self.label
        }
    }
}

impl fmt::Display for LabelError {
    #[cfg(not(feature = "alloc"))]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("invalid label")
    }

    #[cfg(feature = "alloc")]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid label: '{}'", self.label)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for LabelError {}