1use ark_ff::{Field, PrimeField};
2use ark_relations::r1cs::SynthesisError;
3
4use crate::{boolean::Boolean, eq::EqGadget, R1CSVar};
5
6pub trait CmpGadget<F: Field>: R1CSVar<F> + EqGadget<F> {
8 fn is_gt(&self, other: &Self) -> Result<Boolean<F>, SynthesisError> {
9 other.is_lt(self)
10 }
11
12 fn is_ge(&self, other: &Self) -> Result<Boolean<F>, SynthesisError>;
13
14 fn is_lt(&self, other: &Self) -> Result<Boolean<F>, SynthesisError> {
15 Ok(!self.is_ge(other)?)
16 }
17
18 fn is_le(&self, other: &Self) -> Result<Boolean<F>, SynthesisError> {
19 other.is_ge(self)
20 }
21}
22
23impl<F: Field> CmpGadget<F> for () {
25 fn is_gt(&self, _other: &Self) -> Result<Boolean<F>, SynthesisError> {
26 Ok(Boolean::FALSE)
27 }
28
29 fn is_ge(&self, _other: &Self) -> Result<Boolean<F>, SynthesisError> {
30 Ok(Boolean::TRUE)
31 }
32
33 fn is_lt(&self, _other: &Self) -> Result<Boolean<F>, SynthesisError> {
34 Ok(Boolean::FALSE)
35 }
36
37 fn is_le(&self, _other: &Self) -> Result<Boolean<F>, SynthesisError> {
38 Ok(Boolean::TRUE)
39 }
40}
41
42impl<T: CmpGadget<F>, F: PrimeField> CmpGadget<F> for [T] {
44 fn is_ge(&self, other: &Self) -> Result<Boolean<F>, SynthesisError> {
45 let mut result = Boolean::TRUE;
46 let mut all_equal_so_far = Boolean::TRUE;
47 for (a, b) in self.iter().zip(other) {
48 all_equal_so_far &= a.is_eq(b)?;
49 result &= a.is_gt(b)? | &all_equal_so_far;
50 }
51 Ok(result)
52 }
53}