use std::fmt;
use base64::{
alphabet::URL_SAFE,
engine::{general_purpose::NO_PAD, Engine, GeneralPurpose},
};
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 = GeneralPurpose::new(&URL_SAFE, NO_PAD);
Base64Encoded(engine.encode(unencoded))
}
#[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 = GeneralPurpose::new(&URL_SAFE, NO_PAD);
engine
.decode(&self.0)
.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
}