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