snarkvm_synthesizer_program/logic/command/
get.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)]
25pub struct Get<N: Network> {
26 mapping: CallOperator<N>,
28 operands: [Operand<N>; 1],
30 destination: Register<N>,
32}
33
34impl<N: Network> Get<N> {
35 #[inline]
37 pub const fn opcode() -> Opcode {
38 Opcode::Command("get")
39 }
40
41 #[inline]
43 pub fn operands(&self) -> &[Operand<N>] {
44 &self.operands
45 }
46
47 #[inline]
49 pub const fn mapping(&self) -> &CallOperator<N> {
50 &self.mapping
51 }
52
53 #[inline]
55 pub const fn key(&self) -> &Operand<N> {
56 &self.operands[0]
57 }
58
59 #[inline]
61 pub const fn destination(&self) -> &Register<N> {
62 &self.destination
63 }
64
65 #[inline]
67 pub fn contains_external_struct(&self) -> bool {
68 false
69 }
70}
71
72impl<N: Network> Get<N> {
73 #[inline]
75 pub fn finalize(
76 &self,
77 stack: &impl StackTrait<N>,
78 store: &impl FinalizeStoreTrait<N>,
79 registers: &mut impl RegistersTrait<N>,
80 ) -> Result<()> {
81 let (program_id, mapping_name) = match self.mapping {
83 CallOperator::Locator(locator) => (*locator.program_id(), *locator.resource()),
84 CallOperator::Resource(mapping_name) => (*stack.program_id(), mapping_name),
85 };
86
87 if !store.contains_mapping_speculative(&program_id, &mapping_name)? {
89 bail!("Mapping '{program_id}/{mapping_name}' does not exist");
90 }
91
92 let key = registers.load_plaintext(stack, self.key())?;
94
95 let value = match store.get_value_speculative(program_id, mapping_name, &key)? {
97 Some(Value::Plaintext(plaintext)) => Value::Plaintext(plaintext),
98 Some(Value::Record(..)) => bail!("Cannot 'get' a 'record'"),
99 Some(Value::Future(..)) => bail!("Cannot 'get' a 'future'",),
100 None => bail!("Key '{key}' does not exist in mapping '{program_id}/{mapping_name}'"),
102 };
103
104 registers.store(stack, &self.destination, value)?;
106
107 Ok(())
108 }
109}
110
111impl<N: Network> Parser for Get<N> {
112 #[inline]
114 fn parse(string: &str) -> ParserResult<Self> {
115 let (string, _) = Sanitizer::parse(string)?;
117 let (string, _) = tag(*Self::opcode())(string)?;
119 let (string, _) = Sanitizer::parse_whitespaces(string)?;
121
122 let (string, mapping) = CallOperator::parse(string)?;
124 let (string, _) = tag("[")(string)?;
126 let (string, _) = Sanitizer::parse_whitespaces(string)?;
128 let (string, key) = Operand::parse(string)?;
130 let (string, _) = Sanitizer::parse_whitespaces(string)?;
132 let (string, _) = tag("]")(string)?;
134
135 let (string, _) = Sanitizer::parse_whitespaces(string)?;
137 let (string, _) = tag("into")(string)?;
139 let (string, _) = Sanitizer::parse_whitespaces(string)?;
141 let (string, destination) = Register::parse(string)?;
143
144 let (string, _) = Sanitizer::parse_whitespaces(string)?;
146 let (string, _) = tag(";")(string)?;
148
149 Ok((string, Self { mapping, operands: [key], destination }))
150 }
151}
152
153impl<N: Network> FromStr for Get<N> {
154 type Err = Error;
155
156 #[inline]
158 fn from_str(string: &str) -> Result<Self> {
159 match Self::parse(string) {
160 Ok((remainder, object)) => {
161 ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
163 Ok(object)
165 }
166 Err(error) => bail!("Failed to parse string. {error}"),
167 }
168 }
169}
170
171impl<N: Network> Debug for Get<N> {
172 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
174 Display::fmt(self, f)
175 }
176}
177
178impl<N: Network> Display for Get<N> {
179 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
181 write!(f, "{} ", Self::opcode())?;
183 write!(f, "{}[{}] into ", self.mapping, self.key())?;
185 write!(f, "{};", self.destination)
187 }
188}
189
190impl<N: Network> FromBytes for Get<N> {
191 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
193 let mapping = CallOperator::read_le(&mut reader)?;
195 let key = Operand::read_le(&mut reader)?;
197 let destination = Register::read_le(&mut reader)?;
199 Ok(Self { mapping, operands: [key], destination })
201 }
202}
203
204impl<N: Network> ToBytes for Get<N> {
205 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
207 self.mapping.write_le(&mut writer)?;
209 self.key().write_le(&mut writer)?;
211 self.destination.write_le(&mut writer)
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219 use console::{network::MainnetV0, program::Register};
220
221 type CurrentNetwork = MainnetV0;
222
223 #[test]
224 fn test_parse() {
225 let (string, get) = Get::<CurrentNetwork>::parse("get account[r0] into r1;").unwrap();
226 assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
227 assert_eq!(get.mapping, CallOperator::from_str("account").unwrap());
228 assert_eq!(get.operands().len(), 1, "The number of operands is incorrect");
229 assert_eq!(get.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
230 assert_eq!(get.destination, Register::Locator(1), "The second operand is incorrect");
231
232 let (string, get) = Get::<CurrentNetwork>::parse("get token.aleo/balances[r0] into r1;").unwrap();
233 assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
234 assert_eq!(get.mapping, CallOperator::from_str("token.aleo/balances").unwrap());
235 assert_eq!(get.operands().len(), 1, "The number of operands is incorrect");
236 assert_eq!(get.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
237 assert_eq!(get.destination, Register::Locator(1), "The second operand is incorrect");
238 }
239
240 #[test]
241 fn test_from_bytes() {
242 let (string, get) = Get::<CurrentNetwork>::parse("get account[r0] into r1;").unwrap();
243 assert!(string.is_empty());
244 let bytes_le = get.to_bytes_le().unwrap();
245 let result = Get::<CurrentNetwork>::from_bytes_le(&bytes_le[..]);
246 assert!(result.is_ok())
247 }
248}