snarkvm_console_program/state_path/header_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 HeaderLeaf<N> {
19 /// Reads the header leaf from a buffer.
20 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21 // Read the index.
22 let index = FromBytes::read_le(&mut reader)?;
23 // Read the ID.
24 let id = FromBytes::read_le(&mut reader)?;
25 // Return the header leaf.
26 Ok(Self::new(index, id))
27 }
28}
29
30impl<N: Network> ToBytes for HeaderLeaf<N> {
31 /// Writes the header leaf to a buffer.
32 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
33 // Write the index.
34 self.index.write_le(&mut writer)?;
35 // Write the ID.
36 self.id.write_le(&mut writer)
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 const ITERATIONS: u64 = 1000;
45
46 #[test]
47 fn test_bytes() -> Result<()> {
48 let mut rng = TestRng::default();
49
50 for _ in 0..ITERATIONS {
51 // Sample the leaf.
52 let expected = test_helpers::sample_leaf(&mut rng);
53
54 // Check the byte representation.
55 let expected_bytes = expected.to_bytes_le()?;
56 assert_eq!(expected, HeaderLeaf::read_le(&expected_bytes[..])?);
57 }
58 Ok(())
59 }
60}