snarkvm_console_types_boolean/
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> FromBytes for Boolean<E> {
19    /// Reads the boolean 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> ToBytes for Boolean<E> {
27    /// Writes the boolean to a buffer.
28    #[inline]
29    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
30        self.boolean.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    #[test]
44    fn test_bytes() -> Result<()> {
45        let mut rng = TestRng::default();
46
47        for _ in 0..ITERATIONS {
48            // Sample a new boolean.
49            let expected = Boolean::<CurrentEnvironment>::new(Uniform::rand(&mut rng));
50
51            // Check the byte representation.
52            let expected_bytes = expected.to_bytes_le()?;
53            assert_eq!(expected, Boolean::read_le(&expected_bytes[..])?);
54            assert!(Boolean::<CurrentEnvironment>::read_le(&expected_bytes[1..]).is_err());
55        }
56        Ok(())
57    }
58}