mod input;
use input::*;
mod output;
use output::*;
mod bytes;
mod parse;
use crate::Instruction;
use console::{
network::prelude::*,
program::{Identifier, Register},
};
use indexmap::IndexSet;
#[derive(Clone, PartialEq, Eq)]
pub struct Closure<N: Network> {
name: Identifier<N>,
inputs: IndexSet<Input<N>>,
instructions: Vec<Instruction<N>>,
outputs: IndexSet<Output<N>>,
}
impl<N: Network> Closure<N> {
pub fn new(name: Identifier<N>) -> Self {
Self { name, inputs: IndexSet::new(), instructions: Vec::new(), outputs: IndexSet::new() }
}
pub const fn name(&self) -> &Identifier<N> {
&self.name
}
pub const fn inputs(&self) -> &IndexSet<Input<N>> {
&self.inputs
}
pub fn instructions(&self) -> &[Instruction<N>] {
&self.instructions
}
pub const fn outputs(&self) -> &IndexSet<Output<N>> {
&self.outputs
}
}
impl<N: Network> Closure<N> {
#[inline]
fn add_input(&mut self, input: Input<N>) -> Result<()> {
ensure!(self.instructions.is_empty(), "Cannot add inputs after instructions have been added");
ensure!(self.outputs.is_empty(), "Cannot add inputs after outputs have been added");
ensure!(self.inputs.len() <= N::MAX_INPUTS, "Cannot add more than {} inputs", N::MAX_INPUTS);
ensure!(!self.inputs.contains(&input), "Cannot add duplicate input statement");
ensure!(matches!(input.register(), Register::Locator(..)), "Input register must be a locator");
self.inputs.insert(input);
Ok(())
}
#[inline]
pub fn add_instruction(&mut self, instruction: Instruction<N>) -> Result<()> {
ensure!(
self.instructions.len() <= N::MAX_INSTRUCTIONS,
"Cannot add more than {} instructions",
N::MAX_INSTRUCTIONS
);
for register in instruction.destinations() {
ensure!(matches!(register, Register::Locator(..)), "Destination register must be a locator");
}
self.instructions.push(instruction);
Ok(())
}
#[inline]
fn add_output(&mut self, output: Output<N>) -> Result<()> {
ensure!(!self.instructions.is_empty(), "Cannot add outputs before instructions have been added");
ensure!(self.outputs.len() <= N::MAX_OUTPUTS, "Cannot add more than {} outputs", N::MAX_OUTPUTS);
self.outputs.insert(output);
Ok(())
}
}
impl<N: Network> TypeName for Closure<N> {
#[inline]
fn type_name() -> &'static str {
"closure"
}
}