snarkvm_circuit_types_field/
double.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<E: Environment> Double for Field<E> {
19    type Output = Field<E>;
20
21    fn double(&self) -> Self::Output {
22        self + self
23    }
24}
25
26impl<E: Environment> Metrics<dyn Double<Output = Field<E>>> for Field<E> {
27    type Case = Mode;
28
29    fn count(_parameter: &Self::Case) -> Count {
30        Count::is(0, 0, 0, 0)
31    }
32}
33
34impl<E: Environment> OutputMode<dyn Double<Output = Field<E>>> for Field<E> {
35    type Case = Mode;
36
37    fn output_mode(input: &Self::Case) -> Mode {
38        match input.is_constant() {
39            true => Mode::Constant,
40            false => Mode::Private,
41        }
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use snarkvm_circuit_environment::Circuit;
49
50    const ITERATIONS: u64 = 10_000;
51
52    fn check_double(name: &str, mode: Mode, rng: &mut TestRng) {
53        for _ in 0..ITERATIONS {
54            // Sample a random element.
55            let given = Uniform::rand(rng);
56            let candidate = Field::<Circuit>::new(mode, given);
57
58            Circuit::scope(name, || {
59                let result = candidate.double();
60                assert_eq!(given.double(), result.eject_value());
61                assert_count!(Double(Field) => Field, &mode);
62                assert_output_mode!(Double(Field) => Field, &mode, result);
63            });
64        }
65    }
66
67    #[test]
68    fn test_double() {
69        let mut rng = TestRng::default();
70
71        check_double("Constant", Mode::Constant, &mut rng);
72        check_double("Public", Mode::Public, &mut rng);
73        check_double("Private", Mode::Private, &mut rng);
74    }
75
76    #[test]
77    fn test_0_double() {
78        let zero = console::Field::<<Circuit as Environment>::Network>::zero();
79
80        let candidate = Field::<Circuit>::new(Mode::Public, zero).double();
81        assert_eq!(zero, candidate.eject_value());
82    }
83
84    #[test]
85    fn test_1_double() {
86        let one = console::Field::<<Circuit as Environment>::Network>::one();
87        let two = one + one;
88
89        let candidate = Field::<Circuit>::new(Mode::Public, one).double();
90        assert_eq!(two, candidate.eject_value());
91    }
92}