diff --git a/src/nodes/from_str.rs b/src/nodes/from_str.rs index ea7b4c3..4f0f20d 100644 --- a/src/nodes/from_str.rs +++ b/src/nodes/from_str.rs @@ -4,18 +4,8 @@ use rug::{Float, float::ParseFloatError, ops::CompleteRound}; use crate::nodes::{Function, Node, Nodes, Operator, PREC}; -#[derive(Clone, Debug, thiserror::Error)] -pub enum Error { - #[error("unrecognized function/constant: {0}")] - UnrecognizedName(String), - #[error("invalid operator: {0}")] - InvalidOperator(char), - #[error("failed to parse number '{0}': {1}")] - NumberParsing(String, ParseFloatError), -} - impl Node { - fn from_name(s: &str) -> Result { + fn from_name(s: &str) -> Result { Ok(match s { "c" => Self::Number(Float::with_val(PREC, 299_792_458)), "A" => Self::Number(Float::with_val(PREC, 6.02214076e23)), @@ -24,7 +14,7 @@ impl Node { } } impl TryFrom for Operator { - type Error = (); + type Error = char; fn try_from(value: char) -> Result { match value { '+' => Ok(Self::Plus), @@ -32,12 +22,12 @@ impl TryFrom for Operator { '*' => Ok(Self::Mult), '/' => Ok(Self::Div), '^' => Ok(Self::Exp), - _ => Err(()), + _ => Err(value), } } } impl FromStr for Function { - type Err = Error; + type Err = String; fn from_str(s: &str) -> Result { match s { "sin" => Ok(Self::Sine), @@ -48,11 +38,20 @@ impl FromStr for Function { "atan" => Ok(Self::ArcTangent), "sec" => Ok(Self::Secant), "csc" => Ok(Self::CoSecant), - _ => Err(Error::UnrecognizedName(s.to_owned())), + _ => Err(s.to_owned()), } } } +#[derive(Clone, Debug, thiserror::Error)] +pub enum Error { + #[error("unrecognized function/constant: {0}")] + UnrecognizedName(String), + #[error("invalid operator: {0}")] + InvalidOperator(char), + #[error("failed to parse number '{0}': {1}")] + NumberParsing(String, ParseFloatError), +} #[derive(Clone, Debug, Default, PartialEq)] enum ParsingState { #[default] @@ -98,7 +97,10 @@ impl FromStr for Nodes { nodes.push(Node::Operator(Default::default())); } - nodes.push(Node::from_name(&filtered_string[start_index..i])?); + nodes.push( + Node::from_name(&filtered_string[start_index..i]) + .map_err(Error::UnrecognizedName)?, + ); state = ParsingState::Start; } @@ -140,7 +142,7 @@ impl FromStr for Nodes { state = ParsingState::ReadingNumber(i); } else { nodes.push(Node::Operator( - c.try_into().map_err(|()| Error::InvalidOperator(c))?, + c.try_into().map_err(Error::InvalidOperator)?, )); } } @@ -155,7 +157,10 @@ impl FromStr for Nodes { if matches!(nodes.last(), Some(Node::ParenthesisEnd | Node::Number(_))) { nodes.push(Node::Operator(Default::default())); } - nodes.push(Node::from_name(&filtered_string[start_index..i])?); + nodes.push( + Node::from_name(&filtered_string[start_index..i]) + .map_err(Error::UnrecognizedName)?, + ); } ParsingState::ReadingNumber(start_index) => { if matches!(nodes.last(), Some(Node::ParenthesisEnd)) {