Skip to main content

sonobe_primitives/
traits.rs

1//! This module defines helper traits used across Sonobe's crates.
2
3pub use crate::algebra::{
4    field::SonobeField,
5    group::{CF1, CF2, SonobeCurve},
6};
7
8/// [`Dummy`] provides a way to construct a placeholder ("dummy") value of a
9/// given type, parameterized by some configuration `Cfg`.
10///
11/// This is useful when initializing data structures that require a value of a
12/// certain shape before the real data is available, e.g., when setting up the
13/// initial state of a folding scheme.
14pub trait Dummy<Cfg> {
15    /// [`Dummy::dummy`] constructs a dummy value of `Self` based on the given
16    /// configuration `cfg`.
17    fn dummy(cfg: Cfg) -> Self;
18}
19
20impl<T: Default + Clone> Dummy<usize> for Vec<T> {
21    fn dummy(cfg: usize) -> Self {
22        vec![Default::default(); cfg]
23    }
24}
25
26impl<Cfg, T: Dummy<Cfg> + Copy, const N: usize> Dummy<Cfg> for [T; N] {
27    fn dummy(cfg: Cfg) -> Self {
28        [T::dummy(cfg); N]
29    }
30}
31
32impl<Cfg: Copy, A: Dummy<Cfg>, B: Dummy<Cfg>> Dummy<Cfg> for (A, B) {
33    fn dummy(cfg: Cfg) -> Self {
34        (A::dummy(cfg), B::dummy(cfg))
35    }
36}
37
38/// [`Inputize`] converts a value into a vector of field elements, ordered in
39/// the same way as how the value's corresponding in-circuit variable would be
40/// represented in the canonical way in the circuit when allocated as public
41/// input.
42///
43/// This is useful for the verifier to compute the public inputs.
44pub trait Inputize<F> {
45    /// [`Inputize::inputize`] outputs the underlying field elements of `self`
46    /// as if it is allocated in the canonical way in-circuit.
47    fn inputize(&self) -> Vec<F>;
48}
49
50impl<F, T: Inputize<F>> Inputize<F> for [T] {
51    fn inputize(&self) -> Vec<F> {
52        self.iter().flat_map(Inputize::<F>::inputize).collect()
53    }
54}
55
56/// [`InputizeEmulated`] converts a value into a vector of field elements,
57/// ordered in the same way as how the value's corresponding in-circuit variable
58/// would be represented in the emulated way in the circuit when allocated as
59/// public input.
60///
61/// This is useful for the verifier to compute the public inputs.
62///
63/// Note that we require this trait because we need to distinguish between some
64/// data types that can be represented in both the canonical and emulated ways
65/// in-circuit (e.g., field elements or elliptic curve points).
66pub trait InputizeEmulated<F> {
67    /// [`InputizeEmulated::inputize_emulated`] outputs the underlying field
68    /// elements of `self` as if it is allocated in the emulated way in-circuit.
69    fn inputize_emulated(&self) -> Vec<F>;
70}
71
72impl<F, T: InputizeEmulated<F>> InputizeEmulated<F> for [T] {
73    fn inputize_emulated(&self) -> Vec<F> {
74        self.iter()
75            .flat_map(InputizeEmulated::<F>::inputize_emulated)
76            .collect()
77    }
78}