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
use std::fmt;
use base64::{alphabet, decode_engine, encode_engine, engine::fast_portable};
use reqwest::Url;
use serde::{Deserialize, Serialize};
#[macro_export]
macro_rules! impl_base64 {
($a:ty) => {
impl $a {
pub fn from_unencoded(unencoded: impl AsRef<[u8]>) -> Self {
Self { inner: Base64Encoded::from_unencoded(unencoded) }
}
pub fn from_encoded(encoded: impl Into<String>) -> Self {
Self { inner: Base64Encoded::from_encoded(encoded) }
}
pub fn encoded(&self) -> &str { self.inner.encoded() }
pub fn decode(&self) -> Vec<u8> { self.inner.decoded() }
}
};
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub(crate) struct Base64Encoded(String);
impl fmt::Display for Base64Encoded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) }
}
impl AsRef<str> for Base64Encoded {
fn as_ref(&self) -> &str { &self.0 }
}
impl Base64Encoded {
#[allow(dead_code)]
pub(crate) fn from_unencoded(unencoded: impl AsRef<[u8]>) -> Self {
let engine = fast_portable::FastPortable::from(&alphabet::URL_SAFE, fast_portable::NO_PAD);
Base64Encoded(encode_engine(unencoded, &engine))
}
#[allow(dead_code)]
pub(crate) fn from_encoded(encoded: impl Into<String>) -> Self { Base64Encoded(encoded.into()) }
#[allow(dead_code)]
pub(crate) fn decoded(&self) -> Vec<u8> {
let engine = fast_portable::FastPortable::from(&alphabet::URL_SAFE, fast_portable::NO_PAD);
decode_engine(&self.0, &engine).expect("failed to decode, should be safe by construction")
}
#[allow(dead_code)]
pub(crate) fn encoded(&self) -> &str { &self.0 }
}
pub fn add_base64_path_segment<S: AsRef<str>>(mut url: Url, value: S) -> Url {
let new_path = format!("{}base64:{}", url.path(), value.as_ref());
url.set_path(&new_path);
url
}