From 280a88ab6727a012112a277081a92687d7c6a6dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tau=20G=C3=A4rtli?= Date: Sat, 7 Sep 2024 20:24:57 +0200 Subject: [PATCH] Add infallible constructor --- src/theme.rs | 49 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/src/theme.rs b/src/theme.rs index 7b41ff4ab5..77a9e83908 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -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 { - 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)) } } @@ -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 { - 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"), } } }