snarkvm_console_program/state_path/transition_leaf/bytes.rs
1// Copyright 2024 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 TransitionLeaf<N> {
19 /// Reads the transition leaf from a buffer.
20 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21 // Read the version.
22 let version = FromBytes::read_le(&mut reader)?;
23 // Ensure the version is valid.
24 if version != TRANSITION_LEAF_VERSION {
25 return Err(error("Invalid transition leaf version"));
26 }
27 // Read the index.
28 let index = FromBytes::read_le(&mut reader)?;
29 // Read the variant.
30 let variant = FromBytes::read_le(&mut reader)?;
31 // Read the ID.
32 let id = FromBytes::read_le(&mut reader)?;
33 // Return the transition leaf.
34 Ok(Self::from(version, index, variant, id))
35 }
36}
37
38impl<N: Network> ToBytes for TransitionLeaf<N> {
39 /// Writes the transition leaf to a buffer.
40 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
41 // Write the version.
42 self.version.write_le(&mut writer)?;
43 // Write the index.
44 self.index.write_le(&mut writer)?;
45 // Write the variant.
46 self.variant.write_le(&mut writer)?;
47 // Write the ID.
48 self.id.write_le(&mut writer)
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 const ITERATIONS: u64 = 1000;
57
58 #[test]
59 fn test_bytes() -> Result<()> {
60 let mut rng = TestRng::default();
61
62 for _ in 0..ITERATIONS {
63 // Sample the leaf.
64 let expected = test_helpers::sample_leaf(&mut rng);
65
66 // Check the byte representation.
67 let expected_bytes = expected.to_bytes_le()?;
68 assert_eq!(expected, TransitionLeaf::read_le(&expected_bytes[..])?);
69 }
70 Ok(())
71 }
72}