Skip to main content

ssh_encoding/
label.rs

1//! Convenience trait for decoding/encoding string labels.
2
3use crate::{Decode, Decoder, Encode, Error, Reader, Writer};
4use core::{fmt, str::FromStr};
5
6#[cfg(feature = "alloc")]
7use alloc::string::String;
8
9/// Maximum length of an SSH algorithm or method name in bytes ([RFC4251 §6]).
10///
11/// [RFC4251 §6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
12const MAX_LABEL_SIZE: usize = 64;
13
14/// Labels for e.g. cryptographic algorithms.
15///
16/// Receives a blanket impl of [`Decode`] and [`Encode`].
17pub 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/// Errors related to labels.
39#[derive(Clone, Debug, Eq, PartialEq)]
40#[non_exhaustive]
41pub struct LabelError {
42    /// The label that was considered invalid.
43    #[cfg(feature = "alloc")]
44    label: String,
45}
46
47impl LabelError {
48    /// Create a new [`LabelError`] for the given invalid label.
49    ///
50    /// If allocating space for the label fails, the error omits the label.
51    #[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    /// The invalid label string (if available).
67    #[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}