36 lines
1.2 KiB
Rust
36 lines
1.2 KiB
Rust
//! Standard base64 (RFC 4648, with padding), for the SVG logo's data URI.
|
|
|
|
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
|
|
pub(crate) fn encode(data: &[u8]) -> String {
|
|
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
|
for chunk in data.chunks(3) {
|
|
let b = [chunk[0], chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
|
|
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
|
|
for i in 0..4 {
|
|
if i <= chunk.len() {
|
|
out.push(ALPHABET[((n >> (18 - 6 * i)) & 0x3f) as usize] as char);
|
|
} else {
|
|
out.push('=');
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::encode;
|
|
|
|
#[test]
|
|
fn rfc4648_vectors() {
|
|
let cases =
|
|
[("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE=")];
|
|
for (input, expected) in cases {
|
|
assert_eq!(encode(input.as_bytes()), expected);
|
|
}
|
|
assert_eq!(encode(b"foobar"), "Zm9vYmFy");
|
|
assert_eq!(encode(&[0xff, 0xfe, 0xfd]), "//79");
|
|
}
|
|
}
|