ark-r1cs-std/r1cs-std/src/select.rs
r1cs-std/src/select.rsRaw
1use crate::prelude::*;
2use algebra::Field;
3use r1cs_core::SynthesisError;
4
5/// Generates constraints for selecting between one of two values.
6pub trait CondSelectGadget<ConstraintF: Field>
7where
8 Self: Sized,
9{
10 /// If `cond == &Boolean::TRUE`, then this returns `true_value`; else, returns `false_value`.
11 ///
12 /// # Note
13 /// `Self::conditionally_select(cond, true_value, false_value)?` can be more succinctly written as
14 /// `cond.select(&true_value, &false_value)?`.
15 fn conditionally_select(
16 cond: &Boolean<ConstraintF>,
17 true_value: &Self,
18 false_value: &Self,
19 ) -> Result<Self, SynthesisError>;
20}
21
22/// Performs a lookup in a 4-element table using two bits.
23pub trait TwoBitLookupGadget<ConstraintF: Field>
24where
25 Self: Sized,
26{
27 /// The type of values being looked up.
28 type TableConstant;
29
30 /// Interprets the slice `bits` as a two-bit integer `b = bits[0] + (bits[1] << 1)`,
31 /// and then outputs `constants[b]`.
32 ///
33 /// For example, if `bits == [0, 1]`, and `constants == [0, 1, 2, 3]`, this method
34 /// should output a variable corresponding to `2`.
35 ///
36 /// # Panics
37 ///
38 /// This method panics if `bits.len() != 2` or `constants.len() != 4`.
39 fn two_bit_lookup(
40 bits: &[Boolean<ConstraintF>],
41 constants: &[Self::TableConstant],
42 ) -> Result<Self, SynthesisError>;
43}
44
45/// Uses three bits to perform a lookup into a table, where the last bit
46/// conditionally negates the looked-up value.
47pub trait ThreeBitCondNegLookupGadget<ConstraintF: Field>
48where
49 Self: Sized,
50{
51 /// The type of values being looked up.
52 type TableConstant;
53
54 /// Interprets the slice `bits` as a two-bit integer `b = bits[0] + (bits[1] << 1)`,
55 /// and then outputs `constants[b] * c`, where `c = if bits[2] { -1 } else { 1 };`.
56 ///
57 /// That is, `bits[2]` conditionally negates the looked-up value.
58 ///
59 /// For example, if `bits == [1, 0, 1]`, and `constants == [0, 1, 2, 3]`, this method
60 /// should output a variable corresponding to `-1`.
61 ///
62 /// # Panics
63 ///
64 /// This method panics if `bits.len() != 3` or `constants.len() != 4`.
65 fn three_bit_cond_neg_lookup(
66 bits: &[Boolean<ConstraintF>],
67 b0b1: &Boolean<ConstraintF>,
68 constants: &[Self::TableConstant],
69 ) -> Result<Self, SynthesisError>;
70}