Skip to main content

snarkvm_console_types_group/
to_bits.rs

1// Copyright (c) 2019-2026 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<E: Environment> ToBits for Group<E> {
19    /// Outputs the little-endian bit representation of `self.to_x_coordinate()` *without* trailing zeros.
20    fn write_bits_le(&self, vec: &mut Vec<bool>) {
21        self.to_x_coordinate().write_bits_le(vec);
22    }
23
24    /// Outputs the big-endian bit representation of `self.to_x_coordinate()` *without* leading zeros.
25    fn write_bits_be(&self, vec: &mut Vec<bool>) {
26        self.to_x_coordinate().write_bits_be(vec);
27    }
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33    use snarkvm_console_network_environment::Console;
34
35    type CurrentEnvironment = Console;
36
37    const ITERATIONS: u64 = 10_000;
38
39    #[test]
40    fn test_to_bits_le() {
41        let mut rng = TestRng::default();
42
43        for _ in 0..ITERATIONS {
44            // Sample a random value.
45            let group: Group<CurrentEnvironment> = Uniform::rand(&mut rng);
46
47            let candidate = group.to_bits_le();
48            assert_eq!(Group::<CurrentEnvironment>::size_in_bits(), candidate.len());
49
50            for (expected, candidate) in (*group).to_affine().to_x_coordinate().to_bits_le().iter().zip_eq(&candidate) {
51                assert_eq!(expected, candidate);
52            }
53        }
54    }
55
56    #[test]
57    fn test_to_bits_be() {
58        let mut rng = TestRng::default();
59
60        for _ in 0..ITERATIONS {
61            // Sample a random value.
62            let group: Group<CurrentEnvironment> = Uniform::rand(&mut rng);
63
64            let candidate = group.to_bits_be();
65            assert_eq!(Group::<CurrentEnvironment>::size_in_bits(), candidate.len());
66
67            for (expected, candidate) in (*group).to_affine().to_x_coordinate().to_bits_be().iter().zip_eq(&candidate) {
68                assert_eq!(expected, candidate);
69            }
70        }
71    }
72}