ssh_encoding/pem/
encode.rs1use super::{LineEnding, PemLabel, writer::PemWriter};
2use crate::{Encode, Error};
3use core::str;
4
5#[cfg(feature = "alloc")]
6use {super::LINE_WIDTH, alloc::string::String};
7
8#[diagnostic::on_unimplemented(
13 note = "Consider adding impls of `Encode` and `PemLabel` to `{Self}`"
14)]
15pub trait EncodePem: Encode + PemLabel {
16 fn encode_pem<'o>(&self, line_ending: LineEnding, out: &'o mut [u8]) -> Result<&'o str, Error>;
23
24 #[cfg(feature = "alloc")]
31 fn encode_pem_string(&self, line_ending: LineEnding) -> Result<String, Error>;
32}
33
34impl<T: Encode + PemLabel> EncodePem for T {
35 fn encode_pem<'o>(&self, line_ending: LineEnding, out: &'o mut [u8]) -> Result<&'o str, Error> {
36 let mut writer = PemWriter::new(Self::PEM_LABEL, line_ending, out)?;
37 self.encode(&mut writer)?;
38
39 let encoded_len = writer.finish()?;
40 str::from_utf8(&out[..encoded_len]).map_err(Error::from)
41 }
42
43 #[cfg(feature = "alloc")]
44 fn encode_pem_string(&self, line_ending: LineEnding) -> Result<String, Error> {
45 let encoded_len = pem_rfc7468::encapsulated_len_wrapped(
46 Self::PEM_LABEL,
47 LINE_WIDTH,
48 line_ending,
49 self.encoded_len()?,
50 )
51 .map_err(Error::from)?;
52
53 let mut buf = crate::vec_zeroed(encoded_len)?;
54 let actual_len = self.encode_pem(line_ending, &mut buf)?.len();
55 buf.truncate(actual_len);
56 String::from_utf8(buf).map_err(Error::from)
57 }
58}