Reduce unwrap()s.

Relates to #14
This commit is contained in:
Sebastian Schmidt 2021-05-28 09:40:58 +03:00
parent 862bfae920
commit fd3063fc64
3 changed files with 11 additions and 11 deletions

View File

@ -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()));
/// ```

View File

@ -19,24 +19,19 @@ impl<'a> Iterator for NodeIter<'a> {
fn next(&mut self) -> Option<Self::Item> {
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);

View File

@ -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();