Skip to content

Commit ab47b19

Browse files
committed
Impl FromStr for Difficulty
1 parent f759d63 commit ab47b19

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

src/handlers/helpers.rs

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{path::Path, str::FromStr};
1+
use std::{fmt, path::Path, str::FromStr};
22

33
use colored::Colorize;
44
use eyre::Result;
@@ -51,12 +51,26 @@ pub struct DailyChallengeQuestion {
5151
pub titleSlug: String,
5252
}
5353

54+
#[derive(Debug, Clone, Copy)]
5455
pub enum Difficulty {
5556
Easy,
5657
Medium,
5758
Hard,
5859
}
5960

61+
impl FromStr for Difficulty {
62+
type Err = eyre::ErrReport;
63+
64+
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
65+
match s.to_lowercase().as_ref() {
66+
"easy" => Ok(Difficulty::Easy),
67+
"medium" => Ok(Difficulty::Medium),
68+
"hard" => Ok(Difficulty::Hard),
69+
_ => Err(eyre::eyre!("Unknown difficulty")),
70+
}
71+
}
72+
}
73+
6074
#[derive(Debug, Deserialize)]
6175
#[allow(non_snake_case)]
6276
pub struct DailyChallenge {
@@ -99,37 +113,26 @@ impl BoilerPlateCode {
99113
}
100114
}
101115

102-
impl std::fmt::Display for DailyChallenge {
103-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116+
impl fmt::Display for DailyChallenge {
117+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104118
write!(
105119
f,
106120
"Title : {}\nDifficulty : {}\nDate : {}\nStatus : {}\nAC Rate : {:.2}%",
107121
self.question.title.bright_cyan(),
108-
Difficulty::from_str(&self.question.difficulty),
122+
Difficulty::from_str(&self.question.difficulty).map_err(|_| fmt::Error)?,
109123
self.date,
110124
self.userStatus,
111125
self.question.acRate
112126
)
113127
}
114128
}
115129

116-
impl std::fmt::Display for Difficulty {
117-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130+
impl fmt::Display for Difficulty {
131+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118132
match self {
119133
Difficulty::Easy => write!(f, "{}", "Easy".bright_green()),
120134
Difficulty::Medium => write!(f, "{}", "Medium".bright_yellow()),
121135
Difficulty::Hard => write!(f, "{}", "Hard".bright_red()),
122136
}
123137
}
124138
}
125-
126-
impl Difficulty {
127-
pub fn from_str(difficulty: &str) -> Difficulty {
128-
match difficulty {
129-
"Easy" => Difficulty::Easy,
130-
"Medium" => Difficulty::Medium,
131-
"Hard" => Difficulty::Hard,
132-
_ => panic!("Invalid difficulty"),
133-
}
134-
}
135-
}

0 commit comments

Comments
 (0)