From 5511f85d50ad59fd351fabb7e63b6101e742124e Mon Sep 17 00:00:00 2001 From: Odin Dutton Date: Fri, 29 May 2020 03:08:30 +1000 Subject: [PATCH] Implement Color::try_from() (#439) --- src/style/enums/color.rs | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/style/enums/color.rs b/src/style/enums/color.rs index 2b66389..57a151e 100644 --- a/src/style/enums/color.rs +++ b/src/style/enums/color.rs @@ -1,4 +1,4 @@ -use std::{convert::AsRef, str::FromStr}; +use std::{convert::AsRef, convert::TryFrom, result::Result, str::FromStr}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -90,16 +90,11 @@ pub enum Color { AnsiValue(u8), } -impl FromStr for Color { - type Err = (); +impl TryFrom<&str> for Color { + type Error = (); - /// Creates a `Color` from the string representation. - /// - /// # Notes - /// - /// * Returns `Color::White` in case of an unknown color. - /// * Does not return `Err` and you can safely unwrap. - fn from_str(src: &str) -> ::std::result::Result { + /// Try to create a `Color` from the string representation. This returns an error if the string does not match. + fn try_from(src: &str) -> Result { let src = src.to_lowercase(); match src.as_ref() { @@ -119,11 +114,25 @@ impl FromStr for Color { "dark_cyan" => Ok(Color::DarkCyan), "white" => Ok(Color::White), "grey" => Ok(Color::Grey), - _ => Ok(Color::White), + _ => Err(()), } } } +impl FromStr for Color { + type Err = (); + + /// Creates a `Color` from the string representation. + /// + /// # Notes + /// + /// * Returns `Color::White` in case of an unknown color. + /// * Does not return `Err` and you can safely unwrap. + fn from_str(src: &str) -> Result { + Ok(Color::try_from(src).unwrap_or(Color::White)) + } +} + #[cfg(test)] mod tests { use super::Color;