snarkvm_synthesizer_program/constructor/
bytes.rs1use super::*;
17
18impl<N: Network> FromBytes for ConstructorCore<N> {
19 #[inline]
21 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22 let num_commands = u16::read_le(&mut reader)?;
24 if num_commands.is_zero() {
25 return Err(error("Failed to deserialize constructor: needs at least one command"));
26 }
27 if num_commands > u16::try_from(N::MAX_COMMANDS).map_err(error)? {
28 return Err(error(format!("Failed to deserialize constructor: too many commands ({num_commands})")));
29 }
30 let mut commands = Vec::with_capacity((num_commands as usize).min(1024));
33 for _ in 0..num_commands {
34 commands.push(Command::read_le(&mut reader)?);
35 }
36 let mut constructor = Self { commands: Default::default(), num_writes: 0, positions: Default::default() };
38 commands.into_iter().try_for_each(|command| constructor.add_command(command)).map_err(error)?;
39
40 Ok(constructor)
41 }
42}
43
44impl<N: Network> ToBytes for ConstructorCore<N> {
45 #[inline]
47 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
48 let num_commands = self.commands.len();
50 match 0 < num_commands && num_commands <= N::MAX_COMMANDS {
51 true => u16::try_from(num_commands).map_err(error)?.write_le(&mut writer)?,
52 false => return Err(error(format!("Failed to write {num_commands} commands as bytes"))),
53 }
54 for command in self.commands.iter() {
56 command.write_le(&mut writer)?;
57 }
58 Ok(())
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65 use crate::Constructor;
66 use console::network::MainnetV0;
67
68 type CurrentNetwork = MainnetV0;
69
70 #[test]
71 fn test_constructor_bytes() -> Result<()> {
72 let constructor_string = r"
73constructor:
74 add r0 r1 into r2;
75 add r0 r1 into r3;
76 add r0 r1 into r4;
77 add r0 r1 into r5;
78 add r0 r1 into r6;
79 add r0 r1 into r7;
80 add r0 r1 into r8;
81 add r0 r1 into r9;
82 add r0 r1 into r10;
83 add r0 r1 into r11;
84 get accounts[r0] into r12;
85 get accounts[r1] into r13;";
86
87 let expected = Constructor::<CurrentNetwork>::from_str(constructor_string)?;
88 let expected_bytes = expected.to_bytes_le()?;
89 println!("String size: {:?}, Bytecode size: {:?}", constructor_string.len(), expected_bytes.len());
90
91 let candidate = Constructor::<CurrentNetwork>::from_bytes_le(&expected_bytes)?;
92 assert_eq!(expected.to_string(), candidate.to_string());
93 assert_eq!(expected_bytes, candidate.to_bytes_le()?);
94 Ok(())
95 }
96}