use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Category {
Development,
Business,
Marketing,
Design,
Finance,
ItSoftware,
PersonalDevelopment,
Productivity,
Other,
Null,
Unknown(String),
}
impl Category {
#[allow(deprecated)]
pub fn as_str(&self) -> &str {
match self {
Self::Development => "development",
Self::Business => "business",
Self::Marketing => "marketing",
Self::Design => "design",
Self::Finance => "finance",
Self::ItSoftware => "it-software",
Self::PersonalDevelopment => "personal-development",
Self::Productivity => "productivity",
Self::Other => "other",
Self::Null => "null",
Self::Unknown(s) => s.as_str(),
}
}
pub fn is_known(&self) -> bool {
!matches!(self, Self::Unknown(_))
}
}
impl fmt::Display for Category {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl AsRef<str> for Category {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl FromStr for Category {
type Err = std::convert::Infallible;
#[allow(deprecated)]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"development" => Self::Development,
"business" => Self::Business,
"marketing" => Self::Marketing,
"design" => Self::Design,
"finance" => Self::Finance,
"it-software" => Self::ItSoftware,
"personal-development" => Self::PersonalDevelopment,
"productivity" => Self::Productivity,
"other" => Self::Other,
"null" => Self::Null,
other => Self::Unknown(other.to_string()),
})
}
}
impl From<String> for Category {
fn from(s: String) -> Self {
match Self::from_str(&s) {
Ok(Self::Unknown(_)) => Self::Unknown(s),
Ok(other) => other,
}
}
}
impl From<&str> for Category {
fn from(s: &str) -> Self {
Self::from_str(s).unwrap_or_else(|_| Self::Unknown(s.to_string()))
}
}
impl Serialize for Category {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for Category {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Ok(Self::from(s))
}
}