Skip to content

Commit

Permalink
feat: panic trying to mutate stack initial state
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Oct 7, 2024
1 parent 5deecaf commit 030040f
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/parsers/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ impl Stack {
}

pub fn pop(&mut self) {
// Panic if the top element is the initial state.
self.guard_immutable_initial_state();
self.items.pop();
}

pub fn swap_top(&mut self, new_item: State) {
// Panic if the top element is the initial state.
self.guard_immutable_initial_state();
self.items.pop();
self.push(new_item);
}
Expand All @@ -93,14 +93,24 @@ impl Stack {
/// # Panics
///
/// Will panic is the stack is empty. The stack is never empty because it's
/// not allowed to pop the initial state.
/// not allowed to pop or change the initial state.
#[must_use]
pub fn peek(&self) -> State {
match self.items.last() {
Some(top) => top.clone(),
None => panic!("empty stack!"),
}
}

fn guard_immutable_initial_state(&self) {
if let Some(top) = self.items.last() {
if *top != State::Initial {
return;
}
};

panic!("trying to mutate immutable initial state. It can't be popped or swapped!")
}
}

#[cfg(test)]
Expand All @@ -114,6 +124,18 @@ mod tests {
assert_eq!(Stack::default().peek(), State::Initial);
}

#[test]
#[should_panic(expected = "trying to mutate")]
fn not_allow_to_pop_the_initial_state() {
Stack::default().pop();
}

#[test]
#[should_panic(expected = "trying to mutate")]
fn not_allow_to_swap_the_initial_state() {
Stack::default().swap_top(State::Initial);
}

// todo: the rest of operations on the stack.
}
}

0 comments on commit 030040f

Please sign in to comment.