Skip to main content

ssh_encoding/pem/
decode.rs

1use super::{PemLabel, reader::PemReader};
2use crate::{Decode, Error, Reader};
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::Pem`] in the event of PEM decoding errors.
17    /// - Propagates errors returned from the [`Decode::decode`] method.
18    fn decode_pem(pem: impl AsRef<[u8]>) -> Result<Self, Self::Error>;
19}
20
21impl<T: Decode + PemLabel + Sized> DecodePem for T {
22    fn decode_pem(pem: impl AsRef<[u8]>) -> Result<Self, Self::Error> {
23        let mut reader = PemReader::new(pem.as_ref())?;
24        Self::validate_pem_label(reader.type_label()).map_err(Error::from)?;
25
26        let ret = Self::decode(&mut reader)?;
27        Ok(reader.finish(ret)?)
28    }
29}