snarkvm_synthesizer_program/logic/command/
get_or_use.rs1use crate::{CallOperator, FinalizeStoreTrait, Opcode, Operand, RegistersTrait, StackTrait};
17use console::{
18 network::prelude::*,
19 program::{Register, Value},
20};
21
22#[derive(Clone, PartialEq, Eq, Hash)]
26pub struct GetOrUse<N: Network> {
27 mapping: CallOperator<N>,
29 operands: [Operand<N>; 2],
31 destination: Register<N>,
33}
34
35impl<N: Network> GetOrUse<N> {
36 #[inline]
38 pub const fn opcode() -> Opcode {
39 Opcode::Command("get.or_use")
40 }
41
42 #[inline]
44 pub fn operands(&self) -> &[Operand<N>] {
45 &self.operands
46 }
47
48 #[inline]
50 pub const fn mapping(&self) -> &CallOperator<N> {
51 &self.mapping
52 }
53
54 #[inline]
56 pub const fn key(&self) -> &Operand<N> {
57 &self.operands[0]
58 }
59
60 #[inline]
62 pub const fn default(&self) -> &Operand<N> {
63 &self.operands[1]
64 }
65
66 #[inline]
68 pub const fn destination(&self) -> &Register<N> {
69 &self.destination
70 }
71}
72
73impl<N: Network> GetOrUse<N> {
74 #[inline]
76 pub fn finalize(
77 &self,
78 stack: &impl StackTrait<N>,
79 store: &impl FinalizeStoreTrait<N>,
80 registers: &mut impl RegistersTrait<N>,
81 ) -> Result<()> {
82 let (program_id, mapping_name) = match self.mapping {
84 CallOperator::Locator(locator) => (*locator.program_id(), *locator.resource()),
85 CallOperator::Resource(mapping_name) => (*stack.program_id(), mapping_name),
86 };
87
88 if !store.contains_mapping_speculative(&program_id, &mapping_name)? {
90 bail!("Mapping '{program_id}/{mapping_name}' does not exist");
91 }
92
93 let key = registers.load_plaintext(stack, self.key())?;
95
96 let value = match store.get_value_speculative(program_id, mapping_name, &key)? {
98 Some(Value::Plaintext(plaintext)) => Value::Plaintext(plaintext),
99 Some(Value::Record(..)) => bail!("Cannot 'get.or_use' a 'record'"),
100 Some(Value::Future(..)) => bail!("Cannot 'get.or_use' a 'future'"),
101 None => Value::Plaintext(registers.load_plaintext(stack, self.default())?),
103 };
104
105 registers.store(stack, &self.destination, value)?;
107
108 Ok(())
110 }
111}
112
113impl<N: Network> Parser for GetOrUse<N> {
114 #[inline]
116 fn parse(string: &str) -> ParserResult<Self> {
117 let (string, _) = Sanitizer::parse(string)?;
119 let (string, _) = tag(*Self::opcode())(string)?;
121 let (string, _) = Sanitizer::parse_whitespaces(string)?;
123
124 let (string, mapping) = CallOperator::parse(string)?;
126 let (string, _) = tag("[")(string)?;
128 let (string, _) = Sanitizer::parse_whitespaces(string)?;
130 let (string, key) = Operand::parse(string)?;
132 let (string, _) = Sanitizer::parse_whitespaces(string)?;
134 let (string, _) = tag("]")(string)?;
136 let (string, _) = Sanitizer::parse_whitespaces(string)?;
138 let (string, default) = Operand::parse(string)?;
140
141 let (string, _) = Sanitizer::parse_whitespaces(string)?;
143 let (string, _) = tag("into")(string)?;
145 let (string, _) = Sanitizer::parse_whitespaces(string)?;
147 let (string, destination) = Register::parse(string)?;
149
150 let (string, _) = Sanitizer::parse_whitespaces(string)?;
152 let (string, _) = tag(";")(string)?;
154
155 Ok((string, Self { mapping, operands: [key, default], destination }))
156 }
157}
158
159impl<N: Network> FromStr for GetOrUse<N> {
160 type Err = Error;
161
162 #[inline]
164 fn from_str(string: &str) -> Result<Self> {
165 match Self::parse(string) {
166 Ok((remainder, object)) => {
167 ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
169 Ok(object)
171 }
172 Err(error) => bail!("Failed to parse string. {error}"),
173 }
174 }
175}
176
177impl<N: Network> Debug for GetOrUse<N> {
178 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
180 Display::fmt(self, f)
181 }
182}
183
184impl<N: Network> Display for GetOrUse<N> {
185 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
187 write!(f, "{} ", Self::opcode())?;
189 write!(f, "{}[{}] {} into ", self.mapping, self.key(), self.default())?;
191 write!(f, "{};", self.destination)
193 }
194}
195
196impl<N: Network> FromBytes for GetOrUse<N> {
197 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
199 let mapping = CallOperator::read_le(&mut reader)?;
201 let key = Operand::read_le(&mut reader)?;
203 let default = Operand::read_le(&mut reader)?;
205 let destination = Register::read_le(&mut reader)?;
207 Ok(Self { mapping, operands: [key, default], destination })
209 }
210}
211
212impl<N: Network> ToBytes for GetOrUse<N> {
213 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
215 self.mapping.write_le(&mut writer)?;
217 self.key().write_le(&mut writer)?;
219 self.default().write_le(&mut writer)?;
221 self.destination.write_le(&mut writer)
223 }
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229 use console::{network::MainnetV0, program::Register};
230
231 type CurrentNetwork = MainnetV0;
232
233 #[test]
234 fn test_parse() {
235 let (string, get_or_use) = GetOrUse::<CurrentNetwork>::parse("get.or_use account[r0] r1 into r2;").unwrap();
236 assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
237 assert_eq!(get_or_use.mapping, CallOperator::from_str("account").unwrap());
238 assert_eq!(get_or_use.operands().len(), 2, "The number of operands is incorrect");
239 assert_eq!(get_or_use.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
240 assert_eq!(get_or_use.default(), &Operand::Register(Register::Locator(1)), "The second operand is incorrect");
241 assert_eq!(get_or_use.destination, Register::Locator(2), "The second operand is incorrect");
242
243 let (string, get_or_use) =
244 GetOrUse::<CurrentNetwork>::parse("get.or_use token.aleo/balances[r0] r1 into r2;").unwrap();
245 assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
246 assert_eq!(get_or_use.mapping, CallOperator::from_str("token.aleo/balances").unwrap());
247 assert_eq!(get_or_use.operands().len(), 2, "The number of operands is incorrect");
248 assert_eq!(get_or_use.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
249 assert_eq!(get_or_use.default(), &Operand::Register(Register::Locator(1)), "The second operand is incorrect");
250 assert_eq!(get_or_use.destination, Register::Locator(2), "The second operand is incorrect");
251 }
252
253 #[test]
254 fn test_from_bytes() {
255 let (string, get_or_use) = GetOrUse::<CurrentNetwork>::parse("get.or_use account[r0] r1 into r2;").unwrap();
256 assert!(string.is_empty());
257 let bytes_le = get_or_use.to_bytes_le().unwrap();
258 let result = GetOrUse::<CurrentNetwork>::from_bytes_le(&bytes_le[..]);
259 assert!(result.is_ok());
260 }
261}