From 50a6d9d92c77628034b4d22abcc4990aa4cbc26a Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Tue, 24 Mar 2020 15:32:54 +0100 Subject: [PATCH] feat(interface-types) Add the `Stackable::peek1` method. This method allows to peek the last item on the stack (if any) by reference. --- src/interpreter/stack.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/interpreter/stack.rs b/src/interpreter/stack.rs index 7d39b9f..321fcf4 100644 --- a/src/interpreter/stack.rs +++ b/src/interpreter/stack.rs @@ -25,6 +25,10 @@ pub trait Stackable { /// Returned items are in reverse order: the last element comes /// last in the list. fn pop(&mut self, n: usize) -> Option>; + + /// Peek the last item of the stack and returns a reference to it, + /// `None` if the stack is empty. + fn peek1(&self) -> Option<&Self::Item>; } /// A stack implementation of the `Stackable` trait, based on a vector. @@ -85,6 +89,14 @@ where Some(items) } } + + fn peek1(&self) -> Option<&Self::Item> { + if self.inner.is_empty() { + None + } else { + Some(&self.inner[self.inner.len() - 1]) + } + } } #[cfg(test)] @@ -126,4 +138,13 @@ mod tests { assert_eq!(stack.pop1(), None); assert_eq!(stack.is_empty(), true); } + + #[test] + fn test_peek1() { + let mut stack = Stack::new(); + stack.push(1); + stack.push(2); + + assert_eq!(stack.peek1(), Some(&2)); + } }