use crate::{
BASE64_WRAP_WIDTH, Base64Encoder, ENCAPSULATION_BOUNDARY_DELIMITER, Error, LineEnding,
POST_ENCAPSULATION_BOUNDARY, PRE_ENCAPSULATION_BOUNDARY, Result, grammar,
};
use base64ct::{Base64, Encoding};
use core::str;
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "std")]
use std::io;
pub fn encapsulated_len(label: &str, line_ending: LineEnding, input_len: usize) -> Result<usize> {
encapsulated_len_wrapped(label, BASE64_WRAP_WIDTH, line_ending, input_len)
}
pub fn encapsulated_len_wrapped(
label: &str,
line_width: usize,
line_ending: LineEnding,
input_len: usize,
) -> Result<usize> {
if line_width < 4 {
return Err(Error::Length);
}
let base64_len = input_len
.checked_mul(4)
.and_then(|n| n.checked_div(3))
.and_then(|n| n.checked_add(3))
.ok_or(Error::Length)?
& !3;
let base64_len_wrapped = base64_len_wrapped(base64_len, line_width, line_ending)?;
encapsulated_len_inner(label, line_ending, base64_len_wrapped)
}
pub fn encoded_len(label: &str, line_ending: LineEnding, input: &[u8]) -> Result<usize> {
let base64_len = Base64::encoded_len(input);
let base64_len_wrapped = base64_len_wrapped(base64_len, BASE64_WRAP_WIDTH, line_ending)?;
encapsulated_len_inner(label, line_ending, base64_len_wrapped)
}
pub fn encode<'o>(
type_label: &str,
line_ending: LineEnding,
input: &[u8],
buf: &'o mut [u8],
) -> Result<&'o str> {
let mut encoder = Encoder::new(type_label, line_ending, buf)?;
encoder.encode(input)?;
let encoded_len = encoder.finish()?;
let output = &buf[..encoded_len];
debug_assert!(str::from_utf8(output).is_ok());
if output.iter().fold(0u8, |acc, &byte| acc | (byte & 0x80)) == 0 {
#[allow(unsafe_code)]
Ok(unsafe { str::from_utf8_unchecked(output) })
} else {
Err(Error::CharacterEncoding)
}
}
#[cfg(feature = "alloc")]
pub fn encode_string(label: &str, line_ending: LineEnding, input: &[u8]) -> Result<String> {
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)
}
fn encapsulated_len_inner(
label: &str,
line_ending: LineEnding,
base64_len: usize,
) -> Result<usize> {
[
PRE_ENCAPSULATION_BOUNDARY.len(),
label.len(),
ENCAPSULATION_BOUNDARY_DELIMITER.len(),
line_ending.len(),
base64_len,
line_ending.len(),
POST_ENCAPSULATION_BOUNDARY.len(),
label.len(),
ENCAPSULATION_BOUNDARY_DELIMITER.len(),
line_ending.len(),
]
.into_iter()
.try_fold(0usize, |acc, len| acc.checked_add(len))
.ok_or(Error::Length)
}
fn base64_len_wrapped(
base64_len: usize,
line_width: usize,
line_ending: LineEnding,
) -> Result<usize> {
base64_len
.saturating_sub(1)
.checked_div(line_width)
.and_then(|lines| lines.checked_mul(line_ending.len()))
.and_then(|len| len.checked_add(base64_len))
.ok_or(Error::Length)
}
pub struct Encoder<'l, 'o> {
type_label: &'l str,
line_ending: LineEnding,
base64: Base64Encoder<'o>,
}
impl<'l, 'o> Encoder<'l, 'o> {
pub fn new(type_label: &'l str, line_ending: LineEnding, out: &'o mut [u8]) -> Result<Self> {
Self::new_wrapped(type_label, BASE64_WRAP_WIDTH, line_ending, out)
}
pub fn new_wrapped(
type_label: &'l str,
line_width: usize,
line_ending: LineEnding,
mut out: &'o mut [u8],
) -> Result<Self> {
grammar::validate_label(type_label.as_bytes())?;
for boundary_part in [
PRE_ENCAPSULATION_BOUNDARY,
type_label.as_bytes(),
ENCAPSULATION_BOUNDARY_DELIMITER,
line_ending.as_bytes(),
] {
if out.len() < boundary_part.len() {
return Err(Error::Length);
}
let (part, rest) = out.split_at_mut(boundary_part.len());
out = rest;
part.copy_from_slice(boundary_part);
}
let base64 = Base64Encoder::new_wrapped(out, line_width, line_ending)?;
Ok(Self {
type_label,
line_ending,
base64,
})
}
pub fn type_label(&self) -> &'l str {
self.type_label
}
pub fn encode(&mut self, input: &[u8]) -> Result<()> {
self.base64.encode(input)?;
Ok(())
}
pub fn base64_encoder(&mut self) -> &mut Base64Encoder<'o> {
&mut self.base64
}
pub fn finish(self) -> Result<usize> {
let (base64, mut out) = self.base64.finish_with_remaining()?;
for boundary_part in [
self.line_ending.as_bytes(),
POST_ENCAPSULATION_BOUNDARY,
self.type_label.as_bytes(),
ENCAPSULATION_BOUNDARY_DELIMITER,
self.line_ending.as_bytes(),
] {
if out.len() < boundary_part.len() {
return Err(Error::Length);
}
let (part, rest) = out.split_at_mut(boundary_part.len());
out = rest;
part.copy_from_slice(boundary_part);
}
encapsulated_len_inner(self.type_label, self.line_ending, base64.len())
}
}
#[cfg(feature = "std")]
impl io::Write for Encoder<'_, '_> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.encode(buf)?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}