1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use super::chunked_encoder::{ChunkedEncoder, ChunkedEncoderError};
use super::Config;
use std::fmt::{Display, Formatter};
use std::{fmt, str};
#[derive(Debug, PartialEq)]
pub enum DisplayError {
InvalidLineLength,
}
pub struct Base64Display<'a> {
bytes: &'a [u8],
chunked_encoder: ChunkedEncoder,
}
impl<'a> Base64Display<'a> {
pub fn with_config(bytes: &[u8], config: Config) -> Result<Base64Display, DisplayError> {
ChunkedEncoder::new(config)
.map(|c| Base64Display {
bytes,
chunked_encoder: c,
})
.map_err(|e| match e {
ChunkedEncoderError::InvalidLineLength => DisplayError::InvalidLineLength,
})
}
pub fn standard(bytes: &[u8]) -> Base64Display {
Base64Display::with_config(bytes, super::STANDARD).expect("STANDARD is valid")
}
pub fn url_safe(bytes: &[u8]) -> Base64Display {
Base64Display::with_config(bytes, super::URL_SAFE).expect("URL_SAFE is valid")
}
}
impl<'a> Display for Base64Display<'a> {
fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> {
let mut sink = FormatterSink { f: formatter };
self.chunked_encoder.encode(self.bytes, &mut sink)
}
}
struct FormatterSink<'a, 'b: 'a> {
f: &'a mut Formatter<'b>,
}
impl<'a, 'b: 'a> super::chunked_encoder::Sink for FormatterSink<'a, 'b> {
type Error = fmt::Error;
fn write_encoded_bytes(&mut self, encoded: &[u8]) -> Result<(), Self::Error> {
self.f
.write_str(str::from_utf8(encoded).expect("base64 data was not utf8"))
}
}
#[cfg(test)]
mod tests {
use super::super::chunked_encoder::tests::{chunked_encode_matches_normal_encode_random,
SinkTestHelper};
use super::super::*;
use super::*;
#[test]
fn basic_display() {
assert_eq!(
"~$Zm9vYmFy#*",
format!("~${}#*", Base64Display::standard("foobar".as_bytes()))
);
assert_eq!(
"~$Zm9vYmFyZg==#*",
format!("~${}#*", Base64Display::standard("foobarf".as_bytes()))
);
}
#[test]
fn display_encode_matches_normal_encode() {
let helper = DisplaySinkTestHelper;
chunked_encode_matches_normal_encode_random(&helper);
}
struct DisplaySinkTestHelper;
impl SinkTestHelper for DisplaySinkTestHelper {
fn encode_to_string(&self, config: Config, bytes: &[u8]) -> String {
format!("{}", Base64Display::with_config(bytes, config).unwrap())
}
}
}