snarkvm_synthesizer_program/logic/command/
contains.rsuse crate::{
CallOperator,
Opcode,
Operand,
traits::{FinalizeStoreTrait, RegistersLoad, RegistersStore, StackMatches, StackProgram},
};
use console::{
network::prelude::*,
program::{Literal, Register, Value},
types::Boolean,
};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Contains<N: Network> {
mapping: CallOperator<N>,
key: Operand<N>,
destination: Register<N>,
}
impl<N: Network> Contains<N> {
#[inline]
pub const fn opcode() -> Opcode {
Opcode::Command("contains")
}
#[inline]
pub fn operands(&self) -> Vec<Operand<N>> {
vec![self.key.clone()]
}
#[inline]
pub const fn mapping(&self) -> &CallOperator<N> {
&self.mapping
}
#[inline]
pub const fn key(&self) -> &Operand<N> {
&self.key
}
#[inline]
pub const fn destination(&self) -> &Register<N> {
&self.destination
}
}
impl<N: Network> Contains<N> {
#[inline]
pub fn finalize(
&self,
stack: &(impl StackMatches<N> + StackProgram<N>),
store: &impl FinalizeStoreTrait<N>,
registers: &mut (impl RegistersLoad<N> + RegistersStore<N>),
) -> Result<()> {
let (program_id, mapping_name) = match self.mapping {
CallOperator::Locator(locator) => (*locator.program_id(), *locator.resource()),
CallOperator::Resource(mapping_name) => (*stack.program_id(), mapping_name),
};
if !store.contains_mapping_confirmed(&program_id, &mapping_name)? {
bail!("Mapping '{program_id}/{mapping_name}' does not exist in storage");
}
let key = registers.load_plaintext(stack, &self.key)?;
let contains_key = store.contains_key_speculative(program_id, mapping_name, &key)?;
registers.store(stack, &self.destination, Value::from(Literal::Boolean(Boolean::new(contains_key))))?;
Ok(())
}
}
impl<N: Network> Parser for Contains<N> {
#[inline]
fn parse(string: &str) -> ParserResult<Self> {
let (string, _) = Sanitizer::parse(string)?;
let (string, _) = tag(*Self::opcode())(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, mapping) = CallOperator::parse(string)?;
let (string, _) = tag("[")(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, key) = Operand::parse(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, _) = tag("]")(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, _) = tag("into")(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, destination) = Register::parse(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, _) = tag(";")(string)?;
Ok((string, Self { mapping, key, destination }))
}
}
impl<N: Network> FromStr for Contains<N> {
type Err = Error;
#[inline]
fn from_str(string: &str) -> Result<Self> {
match Self::parse(string) {
Ok((remainder, object)) => {
ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
Ok(object)
}
Err(error) => bail!("Failed to parse string. {error}"),
}
}
}
impl<N: Network> Debug for Contains<N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl<N: Network> Display for Contains<N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{} ", Self::opcode())?;
write!(f, "{}[{}] into ", self.mapping, self.key)?;
write!(f, "{};", self.destination)
}
}
impl<N: Network> FromBytes for Contains<N> {
fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
let mapping = CallOperator::read_le(&mut reader)?;
let key = Operand::read_le(&mut reader)?;
let destination = Register::read_le(&mut reader)?;
Ok(Self { mapping, key, destination })
}
}
impl<N: Network> ToBytes for Contains<N> {
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
self.mapping.write_le(&mut writer)?;
self.key.write_le(&mut writer)?;
self.destination.write_le(&mut writer)
}
}
#[cfg(test)]
mod tests {
use super::*;
use console::{network::MainnetV0, program::Register};
type CurrentNetwork = MainnetV0;
#[test]
fn test_parse() {
let (string, contains) = Contains::<CurrentNetwork>::parse("contains account[r0] into r1;").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(contains.mapping, CallOperator::from_str("account").unwrap());
assert_eq!(contains.operands().len(), 1, "The number of operands is incorrect");
assert_eq!(contains.key, Operand::Register(Register::Locator(0)), "The first operand is incorrect");
assert_eq!(contains.destination, Register::Locator(1), "The second operand is incorrect");
let (string, contains) =
Contains::<CurrentNetwork>::parse("contains credits.aleo/account[r0] into r1;").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(contains.mapping, CallOperator::from_str("credits.aleo/account").unwrap());
assert_eq!(contains.operands().len(), 1, "The number of operands is incorrect");
assert_eq!(contains.key, Operand::Register(Register::Locator(0)), "The first operand is incorrect");
assert_eq!(contains.destination, Register::Locator(1), "The second operand is incorrect");
}
#[test]
fn test_from_bytes() {
let (string, contains) = Contains::<CurrentNetwork>::parse("contains account[r0] into r1;").unwrap();
assert!(string.is_empty());
let bytes_le = contains.to_bytes_le().unwrap();
let result = Contains::<CurrentNetwork>::from_bytes_le(&bytes_le[..]);
assert!(result.is_ok())
}
}