100 exercises to learn Rust
This commit is contained in:
46
exercises/05_ticket_v2/14_source/src/status.rs
Normal file
46
exercises/05_ticket_v2/14_source/src/status.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum Status {
|
||||
ToDo,
|
||||
InProgress,
|
||||
Done,
|
||||
}
|
||||
|
||||
impl TryFrom<String> for Status {
|
||||
type Error = ParseStatusError;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
let value = value.to_lowercase();
|
||||
match value.as_str() {
|
||||
"todo" => Ok(Status::ToDo),
|
||||
"inprogress" => Ok(Status::InProgress),
|
||||
"done" => Ok(Status::Done),
|
||||
_ => Err(ParseStatusError {
|
||||
invalid_status: value,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("`{invalid_status}` is not a valid status. Use one of: ToDo, InProgress, Done")]
|
||||
pub struct ParseStatusError {
|
||||
invalid_status: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::convert::TryFrom;
|
||||
|
||||
#[test]
|
||||
fn test_try_from_string() {
|
||||
let status = Status::try_from("ToDO".to_string()).unwrap();
|
||||
assert_eq!(status, Status::ToDo);
|
||||
|
||||
let status = Status::try_from("inproGress".to_string()).unwrap();
|
||||
assert_eq!(status, Status::InProgress);
|
||||
|
||||
let status = Status::try_from("Done".to_string()).unwrap();
|
||||
assert_eq!(status, Status::Done);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user