1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use crate::{ConstraintFieldError, Field, Fp2, Fp2Parameters, PrimeField, ToConstraintField};
use snarkvm_utilities::FromBits;
impl<F: Field> ToConstraintField<F> for () {
#[inline]
fn to_field_elements(&self) -> Result<Vec<F>, ConstraintFieldError> {
Ok(Vec::new())
}
}
impl<F: Field> ToConstraintField<F> for bool {
fn to_field_elements(&self) -> Result<Vec<F>, ConstraintFieldError> {
if *self { Ok(vec![F::one()]) } else { Ok(vec![F::zero()]) }
}
}
impl<F: PrimeField> ToConstraintField<F> for F {
fn to_field_elements(&self) -> Result<Vec<F>, ConstraintFieldError> {
Ok(vec![*self])
}
}
impl<F: Field> ToConstraintField<F> for [F] {
#[inline]
fn to_field_elements(&self) -> Result<Vec<F>, ConstraintFieldError> {
Ok(self.to_vec())
}
}
impl<F: Field> ToConstraintField<F> for Vec<F> {
#[inline]
fn to_field_elements(&self) -> Result<Vec<F>, ConstraintFieldError> {
Ok(self.to_vec())
}
}
impl<P: Fp2Parameters> ToConstraintField<P::Fp> for Fp2<P> {
#[inline]
fn to_field_elements(&self) -> Result<Vec<P::Fp>, ConstraintFieldError> {
let mut c0 = self.c0.to_field_elements()?;
let c1 = self.c1.to_field_elements()?;
c0.extend_from_slice(&c1);
Ok(c0)
}
}
impl<F: PrimeField> ToConstraintField<F> for [bool] {
#[inline]
fn to_field_elements(&self) -> Result<Vec<F>, ConstraintFieldError> {
self.chunks(F::size_in_data_bits())
.map(|chunk| {
F::from_bigint(F::BigInteger::from_bits_le(chunk)?)
.ok_or(ConstraintFieldError::Message("Invalid data bits for constraint field"))
})
.collect::<Result<Vec<F>, _>>()
}
}
impl<F: PrimeField, const NUM_BITS: usize> ToConstraintField<F> for [bool; NUM_BITS] {
#[inline]
fn to_field_elements(&self) -> Result<Vec<F>, ConstraintFieldError> {
self.as_ref().to_field_elements()
}
}
impl<F: PrimeField> ToConstraintField<F> for [u8] {
#[inline]
fn to_field_elements(&self) -> Result<Vec<F>, ConstraintFieldError> {
let floored_field_size_in_bytes = (F::size_in_data_bits() / 8) as usize;
let next_power_of_two = floored_field_size_in_bytes
.checked_next_power_of_two()
.ok_or(ConstraintFieldError::Message("Field size is too large"))?;
Ok(self
.chunks(floored_field_size_in_bytes)
.map(|chunk| {
let mut chunk_vec = vec![0u8; next_power_of_two];
chunk_vec[..chunk.len()].copy_from_slice(chunk);
F::read_le(&*chunk_vec)
})
.collect::<Result<Vec<_>, _>>()?)
}
}
impl<F: PrimeField, const NUM_BYTES: usize> ToConstraintField<F> for [u8; NUM_BYTES] {
#[inline]
fn to_field_elements(&self) -> Result<Vec<F>, ConstraintFieldError> {
self.as_ref().to_field_elements()
}
}