snarkvm_ledger_block/solutions/bytes.rs
1// Copyright (c) 2019-2025 Provable Inc.
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 Solutions<N> {
19 /// Reads the solutions from the buffer.
20 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21 // Read the version.
22 let version: u8 = FromBytes::read_le(&mut reader)?;
23 // Ensure the version is valid.
24 if version != 1 {
25 return Err(error(format!("Invalid solutions version ({version})")));
26 }
27
28 // Read the variant.
29 let variant: u8 = FromBytes::read_le(&mut reader)?;
30 // Parse the variant.
31 match variant {
32 0 => {
33 // Return the solutions.
34 Ok(Self { solutions: None })
35 }
36 1 => {
37 // Read the solutions.
38 let solutions: PuzzleSolutions<N> = FromBytes::read_le(&mut reader)?;
39 // Return the solutions.
40 Self::new(solutions).map_err(error)
41 }
42 _ => Err(error(format!("Invalid solutions variant ({variant})"))),
43 }
44 }
45}
46
47impl<N: Network> ToBytes for Solutions<N> {
48 /// Writes the solutions to the buffer.
49 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
50 // Write the version.
51 1u8.write_le(&mut writer)?;
52
53 match &self.solutions {
54 None => {
55 // Write the variant.
56 0u8.write_le(&mut writer)?;
57 }
58 Some(solutions) => {
59 // Write the variant.
60 1u8.write_le(&mut writer)?;
61 // Write the solutions.
62 solutions.write_le(&mut writer)?;
63 }
64 }
65 Ok(())
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn test_bytes() -> Result<()> {
75 let mut rng = TestRng::default();
76
77 // Sample random solutions.
78 let expected = crate::solutions::serialize::tests::sample_solutions(&mut rng);
79
80 // Check the byte representation.
81 let expected_bytes = expected.to_bytes_le()?;
82 assert_eq!(expected, Solutions::read_le(&expected_bytes[..])?);
83 Ok(())
84 }
85}