Skip to main content

aranya_policy_vm/
stack.rs

1use aranya_policy_module::{TryAsMut, TryFromValue, Value, ValueConversionError};
2
3use crate::error::MachineErrorType;
4
5/// A stack data structure.
6pub trait Stack {
7    /// Push a value (as a [Value]) onto the stack.
8    fn push_value(&mut self, value: Value) -> Result<(), MachineErrorType>;
9
10    /// Pop a value (as a [Value]) from the stack.
11    fn pop_value(&mut self) -> Result<Value, MachineErrorType>;
12
13    /// Peek a value (as a mutable reference to a [Value]) on the top
14    /// of the stack.
15    fn peek_value(&mut self) -> Result<&mut Value, MachineErrorType>;
16
17    /// Push a value onto the stack.
18    fn push<V>(&mut self, value: V) -> Result<(), MachineErrorType>
19    where
20        V: Into<Value>,
21    {
22        self.push_value(value.into())
23    }
24
25    /// Pop a value off of the stack.
26    fn pop<V>(&mut self) -> Result<V, MachineErrorType>
27    where
28        V: TryFromValue,
29    {
30        let raw = self.pop_value()?;
31        Ok(TryFromValue::try_from_value(raw)?)
32    }
33
34    /// Get a reference to the value at the top of the stack
35    fn peek<V>(&mut self) -> Result<&mut V, MachineErrorType>
36    where
37        V: ?Sized,
38        Value: TryAsMut<V, Error = ValueConversionError>,
39    {
40        let raw = self.peek_value()?;
41        Ok(raw.try_as_mut()?)
42    }
43}