base64/
display.rs

1//! Enables base64'd output anywhere you might use a `Display` implementation, like a format string.
2//!
3//! ```
4//! use base64::display::Base64Display;
5//!
6//! let data = vec![0x0, 0x1, 0x2, 0x3];
7//! let wrapper = Base64Display::with_config(&data, base64::STANDARD);
8//!
9//! assert_eq!("base64: AAECAw==", format!("base64: {}", wrapper));
10//! ```
11
12use std::{fmt, str};
13use std::fmt::{Display, Formatter};
14
15use super::chunked_encoder::ChunkedEncoder;
16use super::Config;
17
18/// A convenience wrapper for base64'ing bytes into a format string without heap allocation.
19pub struct Base64Display<'a> {
20    bytes: &'a [u8],
21    chunked_encoder: ChunkedEncoder,
22}
23
24impl<'a> Base64Display<'a> {
25    /// Create a `Base64Display` with the provided config.
26    pub fn with_config(bytes: &[u8], config: Config) -> Base64Display {
27        Base64Display {
28            bytes,
29            chunked_encoder: ChunkedEncoder::new(config),
30        }
31    }
32}
33
34impl<'a> Display for Base64Display<'a> {
35    fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> {
36        let mut sink = FormatterSink { f: formatter };
37        self.chunked_encoder.encode(self.bytes, &mut sink)
38    }
39}
40
41struct FormatterSink<'a, 'b: 'a> {
42    f: &'a mut Formatter<'b>,
43}
44
45impl<'a, 'b: 'a> super::chunked_encoder::Sink for FormatterSink<'a, 'b> {
46    type Error = fmt::Error;
47
48    fn write_encoded_bytes(&mut self, encoded: &[u8]) -> Result<(), Self::Error> {
49        // Avoid unsafe. If max performance is needed, write your own display wrapper that uses
50        // unsafe here to gain about 10-15%.
51        self.f
52            .write_str(str::from_utf8(encoded).expect("base64 data was not utf8"))
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::super::chunked_encoder::tests::{
59        chunked_encode_matches_normal_encode_random, SinkTestHelper,
60    };
61    use super::super::*;
62    use super::*;
63
64    #[test]
65    fn basic_display() {
66        assert_eq!(
67            "~$Zm9vYmFy#*",
68            format!("~${}#*", Base64Display::with_config(b"foobar", STANDARD))
69        );
70        assert_eq!(
71            "~$Zm9vYmFyZg==#*",
72            format!("~${}#*", Base64Display::with_config(b"foobarf", STANDARD))
73        );
74    }
75
76    #[test]
77    fn display_encode_matches_normal_encode() {
78        let helper = DisplaySinkTestHelper;
79        chunked_encode_matches_normal_encode_random(&helper);
80    }
81
82    struct DisplaySinkTestHelper;
83
84    impl SinkTestHelper for DisplaySinkTestHelper {
85        fn encode_to_string(&self, config: Config, bytes: &[u8]) -> String {
86            format!("{}", Base64Display::with_config(bytes, config))
87        }
88    }
89}