use crate::{
global::protocol_structures::instructions::NextExpectedInstructions,
prelude::*,
};
#[derive(Debug, Clone)]
pub enum NextScopeInstruction {
Regular(u32),
RegularUnbounded,
Type(u32),
}
pub enum NextInstructionType {
Regular,
Type,
End,
}
#[derive(Debug, Clone)]
pub struct NotInUnboundedRegularScopeError;
#[derive(Debug, Clone)]
pub struct NextInstructionsStack(Vec<NextScopeInstruction>);
impl Default for NextInstructionsStack {
fn default() -> Self {
NextInstructionsStack(vec![NextScopeInstruction::Regular(1)])
}
}
impl NextInstructionsStack {
pub fn handle_next_expected_instructions(
&mut self,
next_instructions: NextExpectedInstructions,
) -> Result<(), NotInUnboundedRegularScopeError> {
match next_instructions {
NextExpectedInstructions::Regular(regular_count) => {
self.push_next_regular(regular_count);
}
NextExpectedInstructions::UnboundedStart => {
self.push_next_regular_unbounded();
}
NextExpectedInstructions::UnboundedEnd => {
self.pop_unbounded_regular()?;
}
NextExpectedInstructions::Type(type_count) => {
self.push_next_type(type_count);
}
NextExpectedInstructions::RegularAndType(
regular_count,
type_count,
) => {
self.push_next_regular(regular_count);
self.push_next_type(type_count);
}
NextExpectedInstructions::None => {}
}
Ok(())
}
pub fn push_next_regular(&mut self, count: u32) {
if count == 0 {
return;
}
match self.0.last_mut() {
Some(NextScopeInstruction::Regular(existing_count)) => {
if let Some(new_count) = existing_count.checked_add(count) {
*existing_count = new_count;
} else {
self.0.push(NextScopeInstruction::Regular(count));
}
}
_ => {
self.0.push(NextScopeInstruction::Regular(count));
}
}
}
pub fn push_next_regular_unbounded(&mut self) {
self.0.push(NextScopeInstruction::RegularUnbounded);
}
pub fn push_next_type(&mut self, count: u32) {
match self.0.last_mut() {
Some(NextScopeInstruction::Type(existing_count)) => {
if let Some(new_count) = existing_count.checked_add(count) {
*existing_count = new_count;
} else {
self.0.push(NextScopeInstruction::Type(count));
}
}
_ => {
self.0.push(NextScopeInstruction::Type(count));
}
}
}
pub fn pop(&mut self) -> NextInstructionType {
let stack = &mut self.0;
if let Some(top) = stack.last_mut() {
match top {
NextScopeInstruction::Regular(count) => {
if *count > 1 {
*count -= 1;
} else {
stack.pop();
}
NextInstructionType::Regular
}
NextScopeInstruction::RegularUnbounded => {
NextInstructionType::Regular
}
NextScopeInstruction::Type(count) => {
if *count > 1 {
*count -= 1;
} else {
stack.pop();
}
NextInstructionType::Type
}
}
} else {
NextInstructionType::End
}
}
pub fn pop_unbounded_regular(
&mut self,
) -> Result<(), NotInUnboundedRegularScopeError> {
let stack = &mut self.0;
match stack.last() {
Some(NextScopeInstruction::RegularUnbounded) => {
stack.pop();
Ok(())
}
_ => Err(NotInUnboundedRegularScopeError),
}
}
pub fn is_end(&self) -> bool {
self.0.is_empty()
}
}