From d514820011746f6dd1da2511738649bb4cbfde39 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Tue, 8 Mar 2022 07:28:47 -0700 Subject: [PATCH] pem-rfc7468: return `str` from `encode` Changes the return type of `encode` from `[u8]` to `str`. It's easy to go the other direction with `.as_bytes()`. --- pem-rfc7468/src/encoder.rs | 11 +++++++---- pem-rfc7468/src/error.rs | 6 ++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/pem-rfc7468/src/encoder.rs b/pem-rfc7468/src/encoder.rs index 8ff43ce2f..a49a4aa95 100644 --- a/pem-rfc7468/src/encoder.rs +++ b/pem-rfc7468/src/encoder.rs @@ -5,6 +5,7 @@ use crate::{ ENCAPSULATION_BOUNDARY_DELIMITER, POST_ENCAPSULATION_BOUNDARY, PRE_ENCAPSULATION_BOUNDARY, }; use base64ct::{Base64, Encoding}; +use core::str; #[cfg(feature = "alloc")] use alloc::string::String; @@ -18,11 +19,11 @@ pub fn encode<'o>( line_ending: LineEnding, input: &[u8], buf: &'o mut [u8], -) -> Result<&'o [u8]> { +) -> Result<&'o str> { let mut encoder = Encoder::new(type_label, line_ending, buf)?; encoder.encode(input)?; let encoded_len = encoder.finish()?; - Ok(&buf[..encoded_len]) + Ok(str::from_utf8(&buf[..encoded_len])?) } /// Get the length of a PEM encoded document with the given bytes and label. @@ -42,8 +43,10 @@ pub fn encoded_len(label: &str, line_ending: LineEnding, input: &[u8]) -> usize #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub fn encode_string(label: &str, line_ending: LineEnding, input: &[u8]) -> Result { - let mut buf = vec![0u8; encoded_len(label, line_ending, input)]; - encode(label, line_ending, input, &mut buf)?; + let expected_len = encoded_len(label, line_ending, input); + let mut buf = vec![0u8; expected_len]; + let actual_len = encode(label, line_ending, input, &mut buf)?.len(); + debug_assert_eq!(expected_len, actual_len); String::from_utf8(buf).map_err(|_| Error::CharacterEncoding) } diff --git a/pem-rfc7468/src/error.rs b/pem-rfc7468/src/error.rs index b33709cfa..353dd67f9 100644 --- a/pem-rfc7468/src/error.rs +++ b/pem-rfc7468/src/error.rs @@ -72,6 +72,12 @@ impl From for Error { } } +impl From for Error { + fn from(_: core::str::Utf8Error) -> Error { + Error::CharacterEncoding + } +} + #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] impl From for std::io::Error {