use crate::{
traits::{FinalizeStoreTrait, RegistersLoad, RegistersStore, StackMatches, StackProgram},
MappingLocator,
Opcode,
Operand,
};
use console::{
network::prelude::*,
program::{Register, Value},
};
use console::program::Identifier;
use std::io::{BufRead, BufReader};
#[derive(Clone)]
pub struct GetOrUse<N: Network> {
mapping: MappingLocator<N>,
key: Operand<N>,
default: Operand<N>,
destination: Register<N>,
}
impl<N: Network> PartialEq for GetOrUse<N> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.mapping == other.mapping
&& self.key == other.key
&& self.default == other.default
&& self.destination == other.destination
}
}
impl<N: Network> Eq for GetOrUse<N> {}
impl<N: Network> std::hash::Hash for GetOrUse<N> {
#[inline]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.mapping.hash(state);
self.key.hash(state);
self.default.hash(state);
self.destination.hash(state);
}
}
impl<N: Network> GetOrUse<N> {
#[inline]
pub const fn opcode() -> Opcode {
Opcode::Command("get.or_use")
}
#[inline]
pub fn operands(&self) -> Vec<Operand<N>> {
vec![self.key.clone(), self.default.clone()]
}
#[inline]
pub const fn mapping(&self) -> &MappingLocator<N> {
&self.mapping
}
#[inline]
pub const fn key(&self) -> &Operand<N> {
&self.key
}
#[inline]
pub const fn default(&self) -> &Operand<N> {
&self.default
}
#[inline]
pub const fn destination(&self) -> &Register<N> {
&self.destination
}
}
impl<N: Network> GetOrUse<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 {
MappingLocator::Locator(locator) => (*locator.program_id(), *locator.resource()),
MappingLocator::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.or_use' a 'record'"),
Some(Value::Future(..)) => bail!("Cannot 'get.or_use' a '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) = MappingLocator::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, 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>(reader: R) -> IoResult<Self> {
let mut reader = BufReader::with_capacity(1, reader);
let first_byte = {
let buffer = reader.fill_buf()?;
match buffer.first() {
Some(byte) => *byte,
None => return Err(error("Failed to read `get.or_use`. Expected byte.")),
}
};
let mapping = match first_byte {
0u8 => MappingLocator::read_le(&mut reader)?,
_ => MappingLocator::Resource(Identifier::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, key, default, destination })
}
}
impl<N: Network> ToBytes for GetOrUse<N> {
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
match &self.mapping {
MappingLocator::Locator(_) => self.mapping.write_le(&mut writer)?,
MappingLocator::Resource(identifier) => identifier.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::Testnet3, program::Register};
type CurrentNetwork = Testnet3;
pub struct OldGetOrUse<N: Network> {
pub mapping: Identifier<N>,
pub key: Operand<N>,
pub default: Operand<N>,
pub destination: Register<N>,
}
impl<N: Network> ToBytes for OldGetOrUse<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)
}
}
#[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, MappingLocator::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, MappingLocator::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 old_get_or_use = OldGetOrUse::<CurrentNetwork> {
mapping: Identifier::from_str("account").unwrap(),
key: Operand::Register(Register::Locator(0)),
default: Operand::Register(Register::Locator(1)),
destination: Register::Locator(2),
};
let get_or_use_bytes = get_or_use.to_bytes_le().unwrap();
let old_get_or_use_bytes = old_get_or_use.to_bytes_le().unwrap();
let first = GetOrUse::<CurrentNetwork>::from_bytes_le(&get_or_use_bytes[..]).unwrap();
let second = GetOrUse::<CurrentNetwork>::from_bytes_le(&old_get_or_use_bytes[..]).unwrap();
assert_eq!(first, second);
}
}