Skip to main content

ssh_encoding/pem/
decode.rs

1use super::{PemLabel, reader::PemReader};
2use crate::{Decode, Decoder, Error};
3
4/// Decoding trait for PEM documents.
5///
6/// This is an extension trait which is auto-impl'd for types which impl the [`Decode`],
7/// [`PemLabel`], and [`Sized`] traits.
8#[diagnostic::on_unimplemented(
9    note = "Consider adding impls of `Decode` and `PemLabel` to `{Self}`"
10)]
11pub trait DecodePem: Decode + PemLabel + Sized {
12    /// Decode the provided PEM-encoded string, interpreting the Base64-encoded body of the document
13    /// using the [`Decode`] trait.
14    ///
15    /// # Errors
16    /// - Returns [`Error::Length`] if the decoded binary input exceeds `MAX_MSG_SIZE`.
17    /// - Returns [`Error::Pem`] in the event of PEM decoding errors.
18    /// - Propagates errors returned from the [`Decode::decode`] method.
19    fn decode_pem(pem: impl AsRef<[u8]>) -> Result<Self, Self::Error>;
20}
21
22impl<T: Decode + PemLabel + Sized> DecodePem for T {
23    fn decode_pem(pem: impl AsRef<[u8]>) -> Result<Self, Self::Error> {
24        let reader = PemReader::new(pem.as_ref())?;
25        Self::validate_pem_label(reader.type_label()).map_err(Error::from)?;
26
27        let mut decoder = Decoder::new(reader)?;
28        let ret = Self::decode(&mut decoder)?;
29        Ok(decoder.finish(ret)?)
30    }
31}