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
66impl<N: Network> Get<N> {
67 #[inline]
69 pub fn finalize(
70 &self,
71 stack: &impl StackTrait<N>,
72 store: &impl FinalizeStoreTrait<N>,
73 registers: &mut impl RegistersTrait<N>,
74 ) -> Result<()> {
75 let (program_id, mapping_name) = match self.mapping {
77 CallOperator::Locator(locator) => (*locator.program_id(), *locator.resource()),
78 CallOperator::Resource(mapping_name) => (*stack.program_id(), mapping_name),
79 };
80
81 if !store.contains_mapping_speculative(&program_id, &mapping_name)? {
83 bail!("Mapping '{program_id}/{mapping_name}' does not exist");
84 }
85
86 let key = registers.load_plaintext(stack, self.key())?;
88
89 let value = match store.get_value_speculative(program_id, mapping_name, &key)? {
91 Some(Value::Plaintext(plaintext)) => Value::Plaintext(plaintext),
92 Some(Value::Record(..)) => bail!("Cannot 'get' a 'record'"),
93 Some(Value::Future(..)) => bail!("Cannot 'get' a 'future'",),
94 None => bail!("Key '{key}' does not exist in mapping '{program_id}/{mapping_name}'"),
96 };
97
98 registers.store(stack, &self.destination, value)?;
100
101 Ok(())
102 }
103}
104
105impl<N: Network> Parser for Get<N> {
106 #[inline]
108 fn parse(string: &str) -> ParserResult<Self> {
109 let (string, _) = Sanitizer::parse(string)?;
111 let (string, _) = tag(*Self::opcode())(string)?;
113 let (string, _) = Sanitizer::parse_whitespaces(string)?;
115
116 let (string, mapping) = CallOperator::parse(string)?;
118 let (string, _) = tag("[")(string)?;
120 let (string, _) = Sanitizer::parse_whitespaces(string)?;
122 let (string, key) = Operand::parse(string)?;
124 let (string, _) = Sanitizer::parse_whitespaces(string)?;
126 let (string, _) = tag("]")(string)?;
128
129 let (string, _) = Sanitizer::parse_whitespaces(string)?;
131 let (string, _) = tag("into")(string)?;
133 let (string, _) = Sanitizer::parse_whitespaces(string)?;
135 let (string, destination) = Register::parse(string)?;
137
138 let (string, _) = Sanitizer::parse_whitespaces(string)?;
140 let (string, _) = tag(";")(string)?;
142
143 Ok((string, Self { mapping, operands: [key], destination }))
144 }
145}
146
147impl<N: Network> FromStr for Get<N> {
148 type Err = Error;
149
150 #[inline]
152 fn from_str(string: &str) -> Result<Self> {
153 match Self::parse(string) {
154 Ok((remainder, object)) => {
155 ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
157 Ok(object)
159 }
160 Err(error) => bail!("Failed to parse string. {error}"),
161 }
162 }
163}
164
165impl<N: Network> Debug for Get<N> {
166 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
168 Display::fmt(self, f)
169 }
170}
171
172impl<N: Network> Display for Get<N> {
173 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
175 write!(f, "{} ", Self::opcode())?;
177 write!(f, "{}[{}] into ", self.mapping, self.key())?;
179 write!(f, "{};", self.destination)
181 }
182}
183
184impl<N: Network> FromBytes for Get<N> {
185 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
187 let mapping = CallOperator::read_le(&mut reader)?;
189 let key = Operand::read_le(&mut reader)?;
191 let destination = Register::read_le(&mut reader)?;
193 Ok(Self { mapping, operands: [key], destination })
195 }
196}
197
198impl<N: Network> ToBytes for Get<N> {
199 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
201 self.mapping.write_le(&mut writer)?;
203 self.key().write_le(&mut writer)?;
205 self.destination.write_le(&mut writer)
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use console::{network::MainnetV0, program::Register};
214
215 type CurrentNetwork = MainnetV0;
216
217 #[test]
218 fn test_parse() {
219 let (string, get) = Get::<CurrentNetwork>::parse("get account[r0] into r1;").unwrap();
220 assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
221 assert_eq!(get.mapping, CallOperator::from_str("account").unwrap());
222 assert_eq!(get.operands().len(), 1, "The number of operands is incorrect");
223 assert_eq!(get.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
224 assert_eq!(get.destination, Register::Locator(1), "The second operand is incorrect");
225
226 let (string, get) = Get::<CurrentNetwork>::parse("get token.aleo/balances[r0] into r1;").unwrap();
227 assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
228 assert_eq!(get.mapping, CallOperator::from_str("token.aleo/balances").unwrap());
229 assert_eq!(get.operands().len(), 1, "The number of operands is incorrect");
230 assert_eq!(get.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
231 assert_eq!(get.destination, Register::Locator(1), "The second operand is incorrect");
232 }
233
234 #[test]
235 fn test_from_bytes() {
236 let (string, get) = Get::<CurrentNetwork>::parse("get account[r0] into r1;").unwrap();
237 assert!(string.is_empty());
238 let bytes_le = get.to_bytes_le().unwrap();
239 let result = Get::<CurrentNetwork>::from_bytes_le(&bytes_le[..]);
240 assert!(result.is_ok())
241 }
242}