TicketV2/TryFromTrait/Task/src/lib.rs (30 lines of code) (raw):
// TODO: Implement `TryFrom<String>` and `TryFrom<&str>` for `Status`.
// The parsing should be case-insensitive.
#[derive(Debug, PartialEq, Clone)]
pub enum Status {
ToDo,
InProgress,
Done,
}
#[derive(Debug, thiserror::Error)]
#[error("{invalid_status} is not a valid status")]
pub struct ParseStatusError {
invalid_status: String,
}
impl TryFrom<String> for Status {
type Error = ParseStatusError;
fn try_from(value: String) -> Result<Self, Self::Error> {
value.as_str().try_into()
}
}
impl TryFrom<&str> for Status {
type Error = ParseStatusError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value.to_lowercase().as_str() {
"todo" => Ok(Status::ToDo),
"inprogress" => Ok(Status::InProgress),
"done" => Ok(Status::Done),
_ => Err(ParseStatusError {
invalid_status: value.to_string(),
}),
}
}
}