ark_ff/
to_field_vec.rs

1use crate::{biginteger::BigInteger, Field, PrimeField};
2use ark_std::vec::Vec;
3
4/// Types that can be converted to a vector of `F` elements. Useful for
5/// specifying how public inputs to a constraint system should be represented
6/// inside that constraint system.
7pub trait ToConstraintField<F: Field> {
8    fn to_field_elements(&self) -> Option<Vec<F>>;
9}
10
11impl<F: Field> ToConstraintField<F> for bool {
12    fn to_field_elements(&self) -> Option<Vec<F>> {
13        if *self {
14            Some(vec![F::one()])
15        } else {
16            Some(vec![F::zero()])
17        }
18    }
19}
20
21impl<F: PrimeField> ToConstraintField<F> for F {
22    fn to_field_elements(&self) -> Option<Vec<F>> {
23        Some(vec![*self])
24    }
25}
26
27// Impl for base field
28impl<F: Field> ToConstraintField<F> for [F] {
29    #[inline]
30    fn to_field_elements(&self) -> Option<Vec<F>> {
31        Some(self.to_vec())
32    }
33}
34
35impl<ConstraintF: Field> ToConstraintField<ConstraintF> for () {
36    #[inline]
37    fn to_field_elements(&self) -> Option<Vec<ConstraintF>> {
38        Some(Vec::new())
39    }
40}
41
42impl<ConstraintF: PrimeField> ToConstraintField<ConstraintF> for [u8] {
43    #[inline]
44    fn to_field_elements(&self) -> Option<Vec<ConstraintF>> {
45        let max_size = ((ConstraintF::MODULUS_BIT_SIZE - 1) / 8) as usize;
46        let bigint_size = <ConstraintF as PrimeField>::BigInt::NUM_LIMBS * 8;
47        let fes = self
48            .chunks(max_size)
49            .map(|chunk| {
50                let mut bigint = vec![0u8; bigint_size];
51                bigint.iter_mut().zip(chunk).for_each(|(a, b)| *a = *b);
52                ConstraintF::deserialize_compressed(bigint.as_slice()).ok()
53            })
54            .collect::<Option<Vec<_>>>()?;
55        Some(fes)
56    }
57}
58
59impl<ConstraintF: PrimeField> ToConstraintField<ConstraintF> for [u8; 32] {
60    #[inline]
61    fn to_field_elements(&self) -> Option<Vec<ConstraintF>> {
62        self.as_ref().to_field_elements()
63    }
64}
65
66impl<ConstraintF: PrimeField> ToConstraintField<ConstraintF> for Vec<u8> {
67    #[inline]
68    fn to_field_elements(&self) -> Option<Vec<ConstraintF>> {
69        self.as_slice().to_field_elements()
70    }
71}