Skip to main content

ssh_encoding/pem/
reader.rs

1use crate::{Reader, Result};
2use core::fmt;
3
4/// Inner PEM decoder.
5type Inner<'i> = pem_rfc7468::Decoder<'i>;
6
7/// Reader for the Base64 body of a PEM document.
8#[derive(Clone)]
9pub struct PemReader<'i> {
10    /// Inner PEM reader.
11    inner: Inner<'i>,
12}
13
14impl<'i> PemReader<'i> {
15    /// Create a new PEM reader which autodetects the line width of the input.
16    ///
17    /// # Errors
18    /// Returns [`crate::Error::Pem`] on errors parsing the encapsulation or initializing
19    /// the Base64 decoder.
20    pub fn new(pem: &'i [u8]) -> Result<Self> {
21        let inner = Inner::new_detect_wrap(pem)?;
22
23        Ok(Self { inner })
24    }
25
26    /// Get the PEM type label for the input document.
27    #[must_use]
28    pub fn type_label(&self) -> &'i str {
29        self.inner.type_label()
30    }
31}
32
33impl fmt::Debug for PemReader<'_> {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        f.debug_struct("PemReader")
36            .field("remaining_len", &self.remaining_len())
37            .finish_non_exhaustive()
38    }
39}
40
41impl Reader for PemReader<'_> {
42    fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
43        Ok(self.inner.decode(out)?)
44    }
45
46    fn remaining_len(&self) -> usize {
47        self.inner.remaining_len()
48    }
49}