use ::base64::Engine;
use ::base64::engine::GeneralPurpose;
use ::base64::engine::general_purpose::STANDARD;
use ::base64::engine::general_purpose::STANDARD_NO_PAD;
use ::base64::engine::general_purpose::URL_SAFE;
use ::base64::engine::general_purpose::URL_SAFE_NO_PAD;
use qubit_codec::ValueDecoder;
use qubit_codec::ValueEncoder;
use crate::MiscCodecError;
use crate::MiscCodecResult;
#[must_use]
#[derive(Debug, Clone, Copy)]
pub struct Base64Codec {
engine: &'static GeneralPurpose,
}
impl PartialEq for Base64Codec {
#[inline]
fn eq(&self, other: &Self) -> bool {
core::ptr::eq(self.engine, other.engine)
}
}
impl Eq for Base64Codec {}
impl Base64Codec {
#[inline]
pub fn standard() -> Self {
Self { engine: &STANDARD }
}
#[inline]
pub fn standard_no_pad() -> Self {
Self {
engine: &STANDARD_NO_PAD,
}
}
#[inline]
pub fn url_safe() -> Self {
Self { engine: &URL_SAFE }
}
#[inline]
pub fn url_safe_no_pad() -> Self {
Self {
engine: &URL_SAFE_NO_PAD,
}
}
#[inline]
#[must_use]
pub fn encode(&self, bytes: &[u8]) -> String {
self.engine.encode(bytes)
}
#[inline]
pub fn decode(&self, text: &str) -> MiscCodecResult<Vec<u8>> {
self.engine.decode(text).map_err(MiscCodecError::from)
}
}
impl Default for Base64Codec {
#[inline]
fn default() -> Self {
Self::standard()
}
}
impl ValueEncoder<[u8]> for Base64Codec {
type Error = MiscCodecError;
type Output = String;
#[inline(always)]
fn encode(&mut self, input: &[u8]) -> Result<Self::Output, Self::Error> {
Ok(Base64Codec::encode(self, input))
}
}
impl ValueDecoder<str> for Base64Codec {
type Error = MiscCodecError;
type Output = Vec<u8>;
#[inline(always)]
fn decode(&mut self, input: &str) -> Result<Self::Output, Self::Error> {
Base64Codec::decode(self, input)
}
}