Skip to main content

ark_ff/
to_field_vec.rs

1use crate::{biginteger::BigInteger, Field, PrimeField};
2use ark_std::{vec, 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        match self {
14            true => Some(vec![F::one()]),
15            false => Some(vec![F::zero()]),
16        }
17    }
18}
19
20impl<F: PrimeField> ToConstraintField<F> for F {
21    fn to_field_elements(&self) -> Option<Vec<F>> {
22        Some(vec![*self])
23    }
24}
25
26// Impl for base field
27impl<F: Field> ToConstraintField<F> for [F] {
28    #[inline]
29    fn to_field_elements(&self) -> Option<Vec<F>> {
30        Some(self.to_vec())
31    }
32}
33
34impl<ConstraintF: Field> ToConstraintField<ConstraintF> for () {
35    #[inline]
36    fn to_field_elements(&self) -> Option<Vec<ConstraintF>> {
37        Some(Vec::new())
38    }
39}
40
41impl<ConstraintF: PrimeField> ToConstraintField<ConstraintF> for [u8] {
42    #[inline]
43    fn to_field_elements(&self) -> Option<Vec<ConstraintF>> {
44        let max_size = ((ConstraintF::MODULUS_BIT_SIZE - 1) / 8) as usize;
45        let bigint_size = <ConstraintF as PrimeField>::BigInt::NUM_LIMBS * 8;
46        self.chunks(max_size)
47            .map(|chunk| {
48                let mut bigint = vec![0u8; bigint_size];
49                bigint.iter_mut().zip(chunk).for_each(|(a, b)| *a = *b);
50                ConstraintF::deserialize_compressed(bigint.as_slice()).ok()
51            })
52            .collect()
53    }
54}
55
56impl<ConstraintF: PrimeField> ToConstraintField<ConstraintF> for [u8; 32] {
57    #[inline]
58    fn to_field_elements(&self) -> Option<Vec<ConstraintF>> {
59        self.as_ref().to_field_elements()
60    }
61}
62
63impl<ConstraintF: PrimeField> ToConstraintField<ConstraintF> for Vec<u8> {
64    #[inline]
65    fn to_field_elements(&self) -> Option<Vec<ConstraintF>> {
66        self.as_slice().to_field_elements()
67    }
68}