snarkvm_console_types_integers/
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<E: Environment, I: IntegerType> FromBytes for Integer<E, I> {
19    /// Reads the integer from a buffer.
20    #[inline]
21    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22        Ok(Self::new(FromBytes::read_le(&mut reader)?))
23    }
24}
25
26impl<E: Environment, I: IntegerType> ToBytes for Integer<E, I> {
27    /// Writes the integer to a buffer.
28    #[inline]
29    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
30        self.integer.write_le(&mut writer)
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37    use snarkvm_console_network_environment::Console;
38
39    type CurrentEnvironment = Console;
40
41    const ITERATIONS: u64 = 10_000;
42
43    fn check_bytes<I: IntegerType>(rng: &mut TestRng) -> Result<()> {
44        for _ in 0..ITERATIONS {
45            // Sample a random integer.
46            let expected: Integer<CurrentEnvironment, I> = Uniform::rand(rng);
47
48            // Check the byte representation.
49            let expected_bytes = expected.to_bytes_le()?;
50            assert_eq!(expected, Integer::read_le(&expected_bytes[..])?);
51            assert!(Integer::<CurrentEnvironment, I>::read_le(&expected_bytes[1..]).is_err());
52
53            // Dereference the integer and compare bytes.
54            let deref_bytes = (*expected).to_bytes_le()?;
55            for (expected, candidate) in expected_bytes.iter().zip_eq(&deref_bytes) {
56                assert_eq!(expected, candidate);
57            }
58        }
59        Ok(())
60    }
61
62    #[test]
63    fn test_bytes() -> Result<()> {
64        let mut rng = TestRng::default();
65
66        check_bytes::<u8>(&mut rng)?;
67        check_bytes::<u16>(&mut rng)?;
68        check_bytes::<u32>(&mut rng)?;
69        check_bytes::<u64>(&mut rng)?;
70        check_bytes::<u128>(&mut rng)?;
71
72        check_bytes::<i8>(&mut rng)?;
73        check_bytes::<i16>(&mut rng)?;
74        check_bytes::<i32>(&mut rng)?;
75        check_bytes::<i64>(&mut rng)?;
76        check_bytes::<i128>(&mut rng)?;
77
78        Ok(())
79    }
80}