From fd3063fc644e43b13cd339dc623582db81d28da8 Mon Sep 17 00:00:00 2001 From: Sebastian Schmidt Date: Fri, 28 May 2021 09:40:58 +0300 Subject: [PATCH] Reduce unwrap()s. Relates to #14 --- src/context/mod.rs | 2 +- src/tree/iter.rs | 9 ++------- src/tree/mod.rs | 11 ++++++++--- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/context/mod.rs b/src/context/mod.rs index 0925cce..d79cd4e 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -101,7 +101,7 @@ impl Context for HashMapContext { /// let ctx = evalexpr::context_map! { /// "x" => 8, /// "f" => Function::new(Box::new(|_| Ok(42.into()) )) -/// }.unwrap(); +/// }.unwrap(); // Do proper error handling here /// /// assert_eq!(eval_with_context("x + f()", &ctx), Ok(50.into())); /// ``` diff --git a/src/tree/iter.rs b/src/tree/iter.rs index 1bbe8ce..057ee9c 100644 --- a/src/tree/iter.rs +++ b/src/tree/iter.rs @@ -19,24 +19,19 @@ impl<'a> Iterator for NodeIter<'a> { fn next(&mut self) -> Option { loop { - let mut pop_stack = false; let mut result = None; if let Some(last) = self.stack.last_mut() { if let Some(next) = last.next() { result = Some(next); } else { - pop_stack = true; + // Can not fail because we just borrowed last. + self.stack.pop().unwrap(); } } else { return None; } - if pop_stack { - // Can not fail because we borrowed last before. - self.stack.pop().unwrap(); - } - if let Some(result) = result { self.stack.push(result.children.iter()); return Some(result); diff --git a/src/tree/mod.rs b/src/tree/mod.rs index 7cca5d7..e128312 100644 --- a/src/tree/mod.rs +++ b/src/tree/mod.rs @@ -389,13 +389,17 @@ impl Node { if self.operator().is_leaf() { Err(EvalexprError::AppendedToLeafNode) } else if self.has_enough_children() { - if self.children.last().unwrap().operator().precedence() + // Unwrap cannot fail because of has_enough_children + let last_child_operator = self.children.last().unwrap().operator(); + + if last_child_operator.precedence() < node.operator().precedence() // Right-to-left chaining - || (self.children.last().unwrap().operator().precedence() - == node.operator().precedence() && !self.children.last().unwrap().operator().is_left_to_right() && !node.operator().is_left_to_right()) + || (last_child_operator.precedence() + == node.operator().precedence() && !last_child_operator.is_left_to_right() && !node.operator().is_left_to_right()) { // println!("Recursing into {:?}", self.children.last().unwrap().operator()); + // Unwrap cannot fail because of has_enough_children self.children .last_mut() .unwrap() @@ -406,6 +410,7 @@ impl Node { return Err(EvalexprError::AppendedToLeafNode); } + // Unwrap cannot fail because of has_enough_children let last_child = self.children.pop().unwrap(); self.children.push(node); let node = self.children.last_mut().unwrap();