ark-r1cs-std/r1cs-std/src/alloc.rs
r1cs-std/src/alloc.rsRaw
1use algebra::Field;
2use r1cs_core::{ConstraintSystem, SynthesisError};
3use std::borrow::Borrow;
4
5pub trait AllocGadget<V, ConstraintF: Field>
6where
7 Self: Sized,
8 V: ?Sized,
9{
10 fn alloc<F, T, CS: ConstraintSystem<ConstraintF>>(cs: CS, f: F) -> Result<Self, SynthesisError>
11 where
12 F: FnOnce() -> Result<T, SynthesisError>,
13 T: Borrow<V>;
14
15 fn alloc_checked<F, T, CS: ConstraintSystem<ConstraintF>>(cs: CS, f: F) -> Result<Self, SynthesisError>
16 where
17 F: FnOnce() -> Result<T, SynthesisError>,
18 T: Borrow<V>,
19 {
20 Self::alloc(cs, f)
21 }
22
23 fn alloc_input<F, T, CS: ConstraintSystem<ConstraintF>>(cs: CS, f: F) -> Result<Self, SynthesisError>
24 where
25 F: FnOnce() -> Result<T, SynthesisError>,
26 T: Borrow<V>;
27
28 fn alloc_input_checked<F, T, CS: ConstraintSystem<ConstraintF>>(
29 cs: CS,
30 f: F,
31 ) -> Result<Self, SynthesisError>
32 where
33 F: FnOnce() -> Result<T, SynthesisError>,
34 T: Borrow<V>,
35 {
36 Self::alloc_input(cs, f)
37 }
38}
39
40impl<I, ConstraintF: Field, A: AllocGadget<I, ConstraintF>> AllocGadget<[I], ConstraintF> for Vec<A> {
41 fn alloc<F, T, CS: ConstraintSystem<ConstraintF>>(mut cs: CS, f: F) -> Result<Self, SynthesisError>
42 where
43 F: FnOnce() -> Result<T, SynthesisError>,
44 T: Borrow<[I]>,
45 {
46 let mut vec = Vec::new();
47 for (i, value) in f()?.borrow().iter().enumerate() {
48 vec.push(A::alloc(&mut cs.ns(|| format!("value_{}", i)), || {
49 Ok(value)
50 })?);
51 }
52 Ok(vec)
53 }
54
55 fn alloc_input<F, T, CS: ConstraintSystem<ConstraintF>>(mut cs: CS, f: F) -> Result<Self, SynthesisError>
56 where
57 F: FnOnce() -> Result<T, SynthesisError>,
58 T: Borrow<[I]>,
59 {
60 let mut vec = Vec::new();
61 for (i, value) in f()?.borrow().iter().enumerate() {
62 vec.push(A::alloc_input(
63 &mut cs.ns(|| format!("value_{}", i)),
64 || Ok(value),
65 )?);
66 }
67 Ok(vec)
68 }
69
70 fn alloc_checked<F, T, CS: ConstraintSystem<ConstraintF>>(
71 mut cs: CS,
72 f: F,
73 ) -> Result<Self, SynthesisError>
74 where
75 F: FnOnce() -> Result<T, SynthesisError>,
76 T: Borrow<[I]>,
77 {
78 let mut vec = Vec::new();
79 for (i, value) in f()?.borrow().iter().enumerate() {
80 vec.push(A::alloc_checked(
81 &mut cs.ns(|| format!("value_{}", i)),
82 || Ok(value),
83 )?);
84 }
85 Ok(vec)
86 }
87
88 fn alloc_input_checked<F, T, CS: ConstraintSystem<ConstraintF>>(
89 mut cs: CS,
90 f: F,
91 ) -> Result<Self, SynthesisError>
92 where
93 F: FnOnce() -> Result<T, SynthesisError>,
94 T: Borrow<[I]>,
95 {
96 let mut vec = Vec::new();
97 for (i, value) in f()?.borrow().iter().enumerate() {
98 vec.push(A::alloc_input_checked(
99 &mut cs.ns(|| format!("value_{}", i)),
100 || Ok(value),
101 )?);
102 }
103 Ok(vec)
104 }
105}