Skip to content

Commit

Permalink
Add infallible constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
bash committed Sep 7, 2024
1 parent 16d9b99 commit 280a88a
Showing 1 changed file with 36 additions and 13 deletions.
49 changes: 36 additions & 13 deletions src/theme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,19 +71,26 @@ impl Default for ThemePreference {
}
}

impl ThemePreference {
/// Creates a theme preference from a string.
pub fn new(s: &str) -> Self {
use ThemePreference::*;
match s {
"auto" => Auto(Default::default()),
"auto:always" => Auto(DetectColorScheme::Always),
"auto:system" => Auto(DetectColorScheme::System),
"dark" => Dark,
"light" => Light,
_ => Fixed(ThemeName::new(s)),
}
}
}

impl FromStr for ThemePreference {
type Err = Infallible;

fn from_str(s: &str) -> Result<Self, Self::Err> {
use ThemePreference::*;
match s {
"auto" => Ok(Auto(Default::default())),
"auto:always" => Ok(Auto(DetectColorScheme::Always)),
"auto:system" => Ok(Auto(DetectColorScheme::System)),
"dark" => Ok(Dark),
"light" => Ok(Light),
_ => ThemeName::from_str(s).map(Fixed),
}
Ok(ThemePreference::new(s))
}
}

Expand All @@ -101,14 +108,30 @@ pub enum ThemeName {
Default,
}

impl ThemeName {
/// Creates a theme name from a string.
pub fn new(s: &str) -> Self {
if s == "default" {
ThemeName::Default
} else {
ThemeName::Named(s.to_owned())
}
}
}

impl FromStr for ThemeName {
type Err = Infallible;

fn from_str(s: &str) -> Result<Self, Self::Err> {
if s == "default" {
Ok(ThemeName::Default)
} else {
Ok(ThemeName::Named(s.to_owned()))
Ok(ThemeName::new(s))
}
}

impl fmt::Display for ThemeName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ThemeName::Named(t) => f.write_str(t),
ThemeName::Default => f.write_str("default"),
}
}
}
Expand Down

0 comments on commit 280a88a

Please sign in to comment.