use std::{convert::TryFrom, fmt::Display, str::FromStr};
use radix_fmt::radix_36;
use serde::{Deserialize, Serialize, Serializer};
#[derive(Debug, Clone, PartialEq)]
pub struct FullName {
pub(crate) ty: FullNameType,
pub(crate) id: u64,
}
impl Display for FullName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{}_{}", self.ty, radix_36(self.id)))
}
}
impl<'de> Deserialize<'de> for FullName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
FullName::from_str(&String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
impl FromStr for FullName {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (ty, id) = s
.split_once('_')
.ok_or_else(|| "expected an underscore in fullname".to_string())?;
Ok(FullName {
ty: FullNameType::from_str(ty).map_err(|value| value.to_string())?,
id: u64::from_str_radix(id, 36).map_err(|value| value.to_string())?,
})
}
}
impl TryFrom<&str> for FullName {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::from_str(value)
}
}
impl Serialize for FullName {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
#[derive(Debug, Copy, Clone, strum::Display, strum::EnumString, PartialEq)]
pub(crate) enum FullNameType {
#[strum(to_string = "t1")]
Comment,
#[strum(to_string = "t2")]
Account,
#[strum(to_string = "t3")]
Link,
#[strum(to_string = "t4")]
Message,
#[strum(to_string = "t5")]
Subreddit,
#[strum(to_string = "t6")]
Award,
}