Skip to main content

ssh_encoding/base64/
writer.rs

1//! Base64 writer support (constant-time).
2
3use crate::{Result, Writer};
4use core::fmt::{self, Debug};
5
6#[cfg(doc)]
7use crate::Error;
8
9/// Inner constant-time Base64 reader type from the `base64ct` crate.
10type Inner<'o> = base64ct::Encoder<'o, base64ct::Base64>;
11
12/// Constant-time Base64 writer implementation.
13pub struct Base64Writer<'o> {
14    inner: Inner<'o>,
15}
16
17impl<'o> Base64Writer<'o> {
18    /// Create a new Base64 writer which writes output to the given byte slice.
19    ///
20    /// Output constructed using this method is not line-wrapped.
21    ///
22    /// # Errors
23    /// Returns [`Error::Base64`] if the `output` buffer is empty.
24    pub fn new(output: &'o mut [u8]) -> Result<Self> {
25        Ok(Self {
26            inner: Inner::new(output)?,
27        })
28    }
29
30    /// Finish encoding data, returning the resulting Base64 as a `str`.
31    ///
32    /// # Errors
33    /// Returns [`Error::Base64`] if there is insufficient space in the output buffer.
34    pub fn finish(self) -> Result<&'o str> {
35        Ok(self.inner.finish()?)
36    }
37}
38
39impl Debug for Base64Writer<'_> {
40    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
41        f.debug_struct("Base64Writer").finish_non_exhaustive()
42    }
43}
44
45impl Writer for Base64Writer<'_> {
46    fn write(&mut self, bytes: &[u8]) -> Result<()> {
47        Ok(self.inner.encode(bytes)?)
48    }
49}