use crate::errors::ValidationError;
use crate::traits::{PrimitiveValue, ValueObject};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
pub type Base64StringInput = String;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct Base64String(String);
impl ValueObject for Base64String {
type Input = Base64StringInput;
type Error = ValidationError;
fn new(value: Self::Input) -> Result<Self, Self::Error> {
let trimmed = value.trim().to_owned();
if trimmed.is_empty() {
return Err(ValidationError::empty("Base64String"));
}
STANDARD
.decode(&trimmed)
.map_err(|_| ValidationError::invalid("Base64String", &trimmed))?;
Ok(Self(trimmed))
}
fn into_inner(self) -> Self::Input {
self.0
}
}
impl PrimitiveValue for Base64String {
type Primitive = String;
fn value(&self) -> &String {
&self.0
}
}
impl Base64String {
pub fn decode(&self) -> Vec<u8> {
STANDARD.decode(&self.0).expect("already validated")
}
}
impl TryFrom<String> for Base64String {
type Error = ValidationError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::new(s)
}
}
#[cfg(feature = "serde")]
impl From<Base64String> for String {
fn from(v: Base64String) -> String {
v.0
}
}
impl TryFrom<&str> for Base64String {
type Error = ValidationError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value.to_owned())
}
}
impl std::fmt::Display for Base64String {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_valid_base64() {
let b = Base64String::new("aGVsbG8=".into()).unwrap();
assert_eq!(b.value(), "aGVsbG8=");
}
#[test]
fn trims_surrounding_whitespace() {
let b = Base64String::new(" aGVsbG8= ".into()).unwrap();
assert_eq!(b.value(), "aGVsbG8=");
}
#[test]
fn decode_returns_raw_bytes() {
let b = Base64String::new("aGVsbG8=".into()).unwrap();
assert_eq!(b.decode(), b"hello");
}
#[test]
fn rejects_invalid_chars() {
assert!(Base64String::new("not!!valid".into()).is_err());
}
#[test]
fn rejects_wrong_padding() {
assert!(Base64String::new("aGVsbG8".into()).is_err());
}
#[test]
fn rejects_empty() {
assert!(Base64String::new(String::new()).is_err());
}
#[test]
fn try_from_str() {
let b: Base64String = "aGVsbG8=".try_into().unwrap();
assert_eq!(b.decode(), b"hello");
}
#[cfg(feature = "serde")]
#[test]
fn serde_roundtrip() {
let v = Base64String::try_from("aGVsbG8=").unwrap();
let json = serde_json::to_string(&v).unwrap();
let back: Base64String = serde_json::from_str(&json).unwrap();
assert_eq!(v, back);
}
#[cfg(feature = "serde")]
#[test]
fn serde_deserialize_validates() {
let result: Result<Base64String, _> = serde_json::from_str("\"__invalid__\"");
assert!(result.is_err());
}
}