state-macro 0.1.1

Syntax sugar for stateful functions
Documentation
// Stack machine implementation
// This file defines a stack machine with operations: push, pop, swap, add

use std::cell::RefCell;
use std::rc::Rc;

// State: a stack machine with a vector of i32 values
pub type StackState = Rc<RefCell<Vec<i32>>>;

// Create a new empty stack
pub fn new_stack() -> StackState {
    Rc::new(RefCell::new(Vec::new()))
}

// Operations for the stack machine

// Push a value onto the stack
pub fn push(state: &StackState, value: i32) {
    state.borrow_mut().push(value);
}

// Pop a value from the stack (returns 0 if stack is empty)
pub fn pop(state: &StackState) -> i32 {
    state.borrow_mut().pop().unwrap_or(0)
}

// Swap the top two elements on the stack
pub fn swap(state: &StackState) {
    let mut stack = state.borrow_mut();
    let len = stack.len();
    
    if len >= 2 {
        stack.swap(len - 1, len - 2);
    }
}

// Add the top two elements on the stack and push the result
pub fn add(state: &StackState) {
    let mut stack = state.borrow_mut();
    
    if stack.len() >= 2 {
        let a = stack.pop().unwrap();
        let b = stack.pop().unwrap();
        stack.push(a + b);
    }
}

// Access the state directly (helper function for tests)
pub fn get(state: &StackState) -> &StackState {
    state
}