snarkvm_synthesizer_program/logic/command/
get.rsuse crate::{
CallOperator,
Opcode,
Operand,
traits::{FinalizeStoreTrait, RegistersLoad, RegistersStore, StackMatches, StackProgram},
};
use console::{
network::prelude::*,
program::{Register, Value},
};
#[derive(Clone)]
pub struct Get<N: Network> {
mapping: CallOperator<N>,
key: Operand<N>,
destination: Register<N>,
}
impl<N: Network> PartialEq for Get<N> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.mapping == other.mapping && self.key == other.key && self.destination == other.destination
}
}
impl<N: Network> Eq for Get<N> {}
impl<N: Network> std::hash::Hash for Get<N> {
#[inline]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.mapping.hash(state);
self.key.hash(state);
self.destination.hash(state);
}
}
impl<N: Network> Get<N> {
#[inline]
pub const fn opcode() -> Opcode {
Opcode::Command("get")
}
#[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> Get<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 value = match store.get_value_speculative(program_id, mapping_name, &key)? {
Some(Value::Plaintext(plaintext)) => Value::Plaintext(plaintext),
Some(Value::Record(..)) => bail!("Cannot 'get' a 'record'"),
Some(Value::Future(..)) => bail!("Cannot 'get' a 'future'",),
None => bail!("Key '{key}' does not exist in mapping '{program_id}/{mapping_name}'"),
};
registers.store(stack, &self.destination, value)?;
Ok(())
}
}
impl<N: Network> Parser for Get<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 Get<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 Get<N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl<N: Network> Display for Get<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 Get<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 Get<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, get) = Get::<CurrentNetwork>::parse("get account[r0] into r1;").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(get.mapping, CallOperator::from_str("account").unwrap());
assert_eq!(get.operands().len(), 1, "The number of operands is incorrect");
assert_eq!(get.key, Operand::Register(Register::Locator(0)), "The first operand is incorrect");
assert_eq!(get.destination, Register::Locator(1), "The second operand is incorrect");
let (string, get) = Get::<CurrentNetwork>::parse("get token.aleo/balances[r0] into r1;").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(get.mapping, CallOperator::from_str("token.aleo/balances").unwrap());
assert_eq!(get.operands().len(), 1, "The number of operands is incorrect");
assert_eq!(get.key, Operand::Register(Register::Locator(0)), "The first operand is incorrect");
assert_eq!(get.destination, Register::Locator(1), "The second operand is incorrect");
}
#[test]
fn test_from_bytes() {
let (string, get) = Get::<CurrentNetwork>::parse("get account[r0] into r1;").unwrap();
assert!(string.is_empty());
let bytes_le = get.to_bytes_le().unwrap();
let result = Get::<CurrentNetwork>::from_bytes_le(&bytes_le[..]);
assert!(result.is_ok())
}
}