use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Action {
Create,
Update,
Destroy,
}
impl Action {
pub fn as_str(self) -> &'static str {
match self {
Action::Create => "create",
Action::Update => "update",
Action::Destroy => "destroy",
}
}
pub fn is_update(self) -> bool {
matches!(self, Action::Update)
}
}
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Action {
type Err = ParseActionError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"create" => Ok(Action::Create),
"update" | "touch" => Ok(Action::Update),
"destroy" | "delete" => Ok(Action::Destroy),
other => Err(ParseActionError(other.to_owned())),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseActionError(pub String);
impl fmt::Display for ParseActionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid action `{}`", self.0)
}
}
impl std::error::Error for ParseActionError {}