use serde::{self, Deserialize, Serialize};
use std::borrow::Cow;
use std::ops::Deref;
use crate::error::TypeError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TokenError {
#[error("token cannot be empty")]
Empty,
}
macro_rules! define_token_type {
(
$(#[$meta:meta])*
$vis:vis struct $Name:ident;
) => {
$(#[$meta])*
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
$vis struct $Name(String);
impl $Name {
pub fn parse(value: impl AsRef<str>) -> Result<Self, TypeError> {
let raw = value.as_ref().trim();
if raw.is_empty() {
return Err(TypeError::Token(TokenError::Empty));
}
Ok(Self(raw.to_string()))
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[inline]
#[must_use]
pub fn into_inner(self) -> String {
self.0
}
}
impl Deref for $Name {
type Target = str;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsRef<str> for $Name {
#[inline]
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for $Name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl TryFrom<&str> for $Name {
type Error = TypeError;
fn try_from(value: &str) -> Result<Self, TypeError> {
Self::parse(value)
}
}
impl TryFrom<String> for $Name {
type Error = TypeError;
fn try_from(value: String) -> Result<Self, TypeError> {
let trimmed_len = value.trim().len();
if trimmed_len == 0 {
return Err(TypeError::Token(TokenError::Empty));
}
if value.len() == trimmed_len {
Ok(Self(value))
} else {
Self::parse(value)
}
}
}
impl From<$Name> for String {
fn from(value: $Name) -> Self {
value.into_inner()
}
}
impl Serialize for $Name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}
#[allow(unknown_lints)]
impl<'de> Deserialize<'de> for $Name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = Cow::<'de, str>::deserialize(deserializer)?;
match s {
Cow::Borrowed(borrowed) => Self::try_from(borrowed).map_err(serde::de::Error::custom),
Cow::Owned(owned) => Self::try_from(owned).map_err(serde::de::Error::custom),
}
}
}
};
}
define_token_type! {
pub struct AccessToken;
}
define_token_type! {
pub struct RefreshToken;
}
define_token_type! {
pub struct ClientId;
}
define_token_type! {
pub struct ClientSecret;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_should_create_valid_access_token() {
let token = AccessToken::parse(" eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz ").unwrap();
assert_eq!(token.as_str(), "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz"); }
#[test]
fn parse_should_fail_on_empty_token() {
let result = RefreshToken::parse(" ");
assert!(matches!(
result.unwrap_err(),
TypeError::Token(TokenError::Empty)
));
}
#[test]
fn try_from_string_should_reuse_memory_if_clean() {
let raw = String::from("clean_token_123");
let token = AccessToken::try_from(raw).unwrap();
assert_eq!(token.as_ref(), "clean_token_123");
assert_eq!(format!("{}", token), "clean_token_123");
}
#[test]
fn serde_should_support_roundtrip() {
let token = AccessToken::parse("token123").unwrap();
let json = serde_json::to_string(&token).unwrap();
assert_eq!(json, "\"token123\"");
let restored: AccessToken = serde_json::from_str(&json).unwrap();
assert_eq!(token, restored);
}
}