vyre 0.1.0

GPU bytecode condition engine
Documentation
use crate::bytecode::{Instruction, Opcode, Program};
use crate::error::Result;

/// Safe builder for validated bytecode programs.
#[derive(Debug, Default, Clone)]
pub struct ProgramBuilder {
    instructions: Vec<Instruction>,
}

impl ProgramBuilder {
    /// Create an empty builder.
    ///
    /// # Examples
    /// ```
    /// use rulefire::ProgramBuilder;
    ///
    /// let _builder = ProgramBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Append an instruction.
    ///
    /// # Examples
    /// ```
    /// use rulefire::{Opcode, ProgramBuilder};
    ///
    /// let builder = ProgramBuilder::new().push(Opcode::PushTrue, 0).push(Opcode::Halt, 0);
    /// assert_eq!(builder.build().unwrap().instructions.len(), 2);
    /// ```
    pub fn push(mut self, opcode: Opcode, operand: u32) -> Self {
        self.instructions.push(Instruction::new(opcode, operand));
        self
    }

    /// Build and validate the program.
    ///
    /// # Examples
    /// ```
    /// use rulefire::{Opcode, ProgramBuilder};
    ///
    /// let program = ProgramBuilder::new().push(Opcode::Halt, 0).build().unwrap();
    /// assert_eq!(program.instructions.len(), 1);
    /// ```
    pub fn build(self) -> Result<Program> {
        let program = Program {
            instructions: self.instructions,
        };
        program.validate()?;
        Ok(program)
    }
}