snarkvm_ledger_puzzle/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 PuzzleSolutions<N> {
19    /// Reads the solutions from the buffer.
20    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21        // Read the number of solutions.
22        let num_solutions: u8 = FromBytes::read_le(&mut reader)?;
23        // Ensure the number of solutions is within bounds.
24        if num_solutions as usize > N::MAX_SOLUTIONS {
25            return Err(error("Failed to read solutions: too many solutions"));
26        }
27        // Read the solutions.
28        let mut solutions = Vec::with_capacity(num_solutions as usize);
29        for _ in 0..num_solutions {
30            solutions.push(Solution::read_le(&mut reader)?);
31        }
32        // Return the solutions.
33        Self::new(solutions).map_err(error)
34    }
35}
36
37impl<N: Network> ToBytes for PuzzleSolutions<N> {
38    /// Writes the solutions to the buffer.
39    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
40        // Write the number of solutions.
41        (u8::try_from(self.solutions.len()).map_err(error)?).write_le(&mut writer)?;
42        // Write the solutions.
43        for solution in self.solutions.values() {
44            solution.write_le(&mut writer)?;
45        }
46        Ok(())
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn test_bytes() -> Result<()> {
56        let mut rng = TestRng::default();
57
58        // Sample random solutions.
59        let expected = crate::solutions::serialize::tests::sample_solutions(&mut rng);
60
61        // Check the byte representation.
62        let expected_bytes = expected.to_bytes_le()?;
63        assert_eq!(expected, PuzzleSolutions::read_le(&expected_bytes[..])?);
64        Ok(())
65    }
66}