snarkvm_synthesizer_program/logic/instruction/bytes.rs
1// Copyright 2024-2025 Aleo Network Foundation
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<N: Network> FromBytes for Instruction<N> {
19 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
20 /// Creates a match statement that produces the `FromBytes` implementation for the given instruction.
21 ///
22 /// ## Example
23 /// ```ignore
24 /// instruction_from_bytes_le!(self, |reader| {}, { Add, Sub, Mul, Div })
25 /// ```
26 macro_rules! instruction_from_bytes_le {
27 ($object:expr, |$reader:ident| $_operation:block, { $( $variant:ident, )+ }) => {{
28 // Read the opcode index.
29 let index = u16::read_le(&mut $reader)?;
30
31 // Build the cases for all instructions.
32 if index as usize >= Instruction::<N>::OPCODES.len() {
33 return Err(error(format!("Failed to deserialize an instruction: invalid opcode index ({index})")));
34 }
35 $(if Instruction::<N>::OPCODES[index as usize] == $variant::<N>::opcode() {
36 // Read the instruction.
37 let instruction = $variant::read_le(&mut $reader)?;
38 // Return the instruction.
39 return Ok(Self::$variant(instruction));
40 })+
41 // If the index is out of bounds, return an error.
42 Err(error(format!("Failed to deserialize an instruction of opcode index '{index}'")))
43 }};
44 }
45 // Execute the `from_bytes_le` method.
46 crate::instruction!(instruction_from_bytes_le!(self, reader))
47 }
48}
49
50impl<N: Network> ToBytes for Instruction<N> {
51 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
52 /// Creates a match statement that produces the `ToBytes` implementation for the given instruction.
53 ///
54 /// ## Example
55 /// ```ignore
56 /// instruction_to_bytes_le!(self, |writer| {}, { Add, Sub, Mul, Div })
57 /// ```
58 macro_rules! instruction_to_bytes_le {
59 ($object:expr, |$writer:ident| $_operation:block, { $( $variant:ident, )+ }) => {{
60 // Build the match cases.
61 match $object {
62 $(Self::$variant(instruction) => {
63 // Retrieve the opcode index.
64 // Note: This unwrap is guaranteed to succeed because the opcode variant is known to exist.
65 let index = Instruction::<N>::OPCODES.iter().position(|&opcode| $variant::<N>::opcode() == opcode).unwrap();
66
67 // Serialize the instruction.
68 // Note that this cast is safe as the number of instructions is less than `u16::MAX`.
69 #[allow(clippy::cast_possible_truncation)]
70 u16::write_le(&(index as u16),&mut $writer)?;
71 instruction.write_le(&mut $writer)?;
72 }),+
73 }
74 Ok(())
75 }};
76 }
77 // Execute the `to_bytes_le` method.
78 crate::instruction!(instruction_to_bytes_le!(self, writer))
79 }
80}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85 use console::network::MainnetV0;
86
87 type CurrentNetwork = MainnetV0;
88
89 #[test]
90 fn test_bytes() -> Result<()> {
91 let instruction = "add r0 r1 into r2;";
92 let expected = Instruction::<CurrentNetwork>::from_str(instruction)?;
93 let expected_bytes = expected.to_bytes_le()?;
94
95 let candidate = Instruction::<CurrentNetwork>::from_bytes_le(&expected_bytes)?;
96 assert_eq!(expected_bytes, candidate.to_bytes_le()?);
97 Ok(())
98 }
99}