ark-r1cs-std/src/fields/emulated_fp/mul_result.rs
src/fields/emulated_fp/mul_result.rsRaw
1use super::{AllocatedMulResultVar, EmulatedFpVar};
2use ark_ff::PrimeField;
3use ark_relations::r1cs::Result as R1CSResult;
4
5/// An intermediate representation especially for the result of a
6/// multiplication, containing more limbs. It is intended for advanced usage to
7/// improve the efficiency.
8///
9/// That is, instead of calling `mul`, one can call `mul_without_reduce` to
10/// obtain this intermediate representation, which can still be added.
11/// Then, one can call `reduce` to reduce it back to `EmulatedFpVar`.
12/// This may help cut the number of reduce operations.
13#[derive(Debug)]
14#[must_use]
15pub enum MulResultVar<TargetF: PrimeField, BaseF: PrimeField> {
16 /// as a constant
17 Constant(TargetF),
18 /// as an allocated gadget
19 Var(AllocatedMulResultVar<TargetF, BaseF>),
20}
21
22impl<TargetF: PrimeField, BaseF: PrimeField> MulResultVar<TargetF, BaseF> {
23 /// Create a zero `MulResultVar` (used for additions)
24 pub fn zero() -> Self {
25 Self::Constant(TargetF::zero())
26 }
27
28 /// Create an `MulResultVar` from a constant
29 pub fn constant(v: TargetF) -> Self {
30 Self::Constant(v)
31 }
32
33 /// Reduce the `MulResultVar` back to EmulatedFpVar
34 #[tracing::instrument(target = "r1cs")]
35 pub fn reduce(&self) -> R1CSResult<EmulatedFpVar<TargetF, BaseF>> {
36 match self {
37 Self::Constant(c) => Ok(EmulatedFpVar::Constant(*c)),
38 Self::Var(v) => Ok(EmulatedFpVar::Var(v.reduce()?)),
39 }
40 }
41}
42
43impl<TargetF: PrimeField, BaseF: PrimeField> From<&EmulatedFpVar<TargetF, BaseF>>
44 for MulResultVar<TargetF, BaseF>
45{
46 fn from(src: &EmulatedFpVar<TargetF, BaseF>) -> Self {
47 match src {
48 EmulatedFpVar::Constant(c) => MulResultVar::Constant(*c),
49 EmulatedFpVar::Var(v) => {
50 MulResultVar::Var(AllocatedMulResultVar::<TargetF, BaseF>::from(v))
51 },
52 }
53 }
54}
55
56impl_bounded_ops!(
57 MulResultVar<TargetF, BaseF>,
58 TargetF,
59 Add,
60 add,
61 AddAssign,
62 add_assign,
63 |this: &'a MulResultVar<TargetF, BaseF>, other: &'a MulResultVar<TargetF, BaseF>| {
64 use MulResultVar::*;
65 match (this, other) {
66 (Constant(c1), Constant(c2)) => Constant(*c1 + c2),
67 (Constant(c), Var(v)) | (Var(v), Constant(c)) => Var(v.add_constant(c).unwrap()),
68 (Var(v1), Var(v2)) => Var(v1.add(v2).unwrap()),
69 }
70 },
71 |this: &'a MulResultVar<TargetF, BaseF>, other: TargetF| { this + &MulResultVar::Constant(other) },
72 (TargetF: PrimeField, BaseF: PrimeField),
73);