use crate::{CallOperator, FinalizeStoreTrait, Opcode, Operand, RegistersTrait, StackTrait};
use console::{
network::prelude::*,
program::{Register, Value},
};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct GetOrUse<N: Network> {
mapping: CallOperator<N>,
operands: [Operand<N>; 2],
destination: Register<N>,
}
impl<N: Network> GetOrUse<N> {
#[inline]
pub const fn opcode() -> Opcode {
Opcode::Command("get.or_use")
}
#[inline]
pub fn operands(&self) -> &[Operand<N>] {
&self.operands
}
#[inline]
pub const fn mapping(&self) -> &CallOperator<N> {
&self.mapping
}
#[inline]
pub const fn key(&self) -> &Operand<N> {
&self.operands[0]
}
#[inline]
pub const fn default(&self) -> &Operand<N> {
&self.operands[1]
}
#[inline]
pub const fn destination(&self) -> &Register<N> {
&self.destination
}
#[inline]
pub fn contains_external_struct(&self) -> bool {
false
}
}
impl<N: Network> GetOrUse<N> {
#[inline]
pub fn finalize(
&self,
stack: &impl StackTrait<N>,
store: &impl FinalizeStoreTrait<N>,
registers: &mut impl RegistersTrait<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_speculative(&program_id, &mapping_name)? {
bail!("Mapping '{program_id}/{mapping_name}' does not exist");
}
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.or_use' a 'record'"),
Some(Value::Future(..)) => bail!("Cannot 'get.or_use' a 'future'"),
Some(Value::DynamicRecord(..)) => bail!("Cannot 'get.or_use' a 'dynamic.record'"),
Some(Value::DynamicFuture(..)) => bail!("Cannot 'get.or_use' a 'dynamic.future'"),
None => Value::Plaintext(registers.load_plaintext(stack, self.default())?),
};
registers.store(stack, &self.destination, value)?;
Ok(())
}
}
impl<N: Network> Parser for GetOrUse<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, default) = Operand::parse(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, operands: [key, default], destination }))
}
}
impl<N: Network> FromStr for GetOrUse<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 GetOrUse<N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl<N: Network> Display for GetOrUse<N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{} ", Self::opcode())?;
write!(f, "{}[{}] {} into ", self.mapping, self.key(), self.default())?;
write!(f, "{};", self.destination)
}
}
impl<N: Network> FromBytes for GetOrUse<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 default = Operand::read_le(&mut reader)?;
let destination = Register::read_le(&mut reader)?;
Ok(Self { mapping, operands: [key, default], destination })
}
}
impl<N: Network> ToBytes for GetOrUse<N> {
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
self.mapping.write_le(&mut writer)?;
self.key().write_le(&mut writer)?;
self.default().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_or_use) = GetOrUse::<CurrentNetwork>::parse("get.or_use account[r0] r1 into r2;").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(get_or_use.mapping, CallOperator::from_str("account").unwrap());
assert_eq!(get_or_use.operands().len(), 2, "The number of operands is incorrect");
assert_eq!(get_or_use.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
assert_eq!(get_or_use.default(), &Operand::Register(Register::Locator(1)), "The second operand is incorrect");
assert_eq!(get_or_use.destination, Register::Locator(2), "The second operand is incorrect");
let (string, get_or_use) =
GetOrUse::<CurrentNetwork>::parse("get.or_use token.aleo/balances[r0] r1 into r2;").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(get_or_use.mapping, CallOperator::from_str("token.aleo/balances").unwrap());
assert_eq!(get_or_use.operands().len(), 2, "The number of operands is incorrect");
assert_eq!(get_or_use.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
assert_eq!(get_or_use.default(), &Operand::Register(Register::Locator(1)), "The second operand is incorrect");
assert_eq!(get_or_use.destination, Register::Locator(2), "The second operand is incorrect");
}
#[test]
fn test_from_bytes() {
let (string, get_or_use) = GetOrUse::<CurrentNetwork>::parse("get.or_use account[r0] r1 into r2;").unwrap();
assert!(string.is_empty());
let bytes_le = get_or_use.to_bytes_le().unwrap();
let result = GetOrUse::<CurrentNetwork>::from_bytes_le(&bytes_le[..]);
assert!(result.is_ok());
}
}