snarkvm_circuit_environment/traits/
inject.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::Mode;
17
18/// Operations to inject from a primitive form into a circuit environment.
19pub trait Inject {
20    type Primitive;
21
22    ///
23    /// Initializes a circuit of the given mode and primitive value.
24    ///
25    fn new(mode: Mode, value: Self::Primitive) -> Self;
26
27    ///
28    /// Initializes a constant of the given primitive value.
29    ///
30    fn constant(value: Self::Primitive) -> Self
31    where
32        Self: Sized,
33    {
34        Self::new(Mode::Constant, value)
35    }
36}
37
38/********************/
39/***** IndexMap *****/
40/********************/
41
42impl<C0: Eq + core::hash::Hash + Inject<Primitive = P0>, C1: Inject<Primitive = P1>, P0, P1> Inject
43    for indexmap::IndexMap<C0, C1>
44{
45    type Primitive = indexmap::IndexMap<P0, P1>;
46
47    #[inline]
48    fn new(mode: Mode, value: Self::Primitive) -> Self {
49        value.into_iter().map(|(v0, v1)| (C0::new(mode, v0), C1::new(mode, v1))).collect()
50    }
51}
52
53/********************/
54/****** Arrays ******/
55/********************/
56
57impl<C: Inject<Primitive = P>, P> Inject for Vec<C> {
58    type Primitive = Vec<P>;
59
60    #[inline]
61    fn new(mode: Mode, value: Self::Primitive) -> Self {
62        value.into_iter().map(|v| C::new(mode, v)).collect()
63    }
64}
65
66/********************/
67/****** Tuples ******/
68/********************/
69
70/// A helper macro to implement `Inject` for a tuple of `Inject` circuits.
71macro_rules! inject_tuple {
72    (($t0:ident, 0), $(($ty:ident, $idx:tt)),*) => {
73        impl<$t0: Inject, $($ty: Inject),*> Inject for ($t0, $($ty),*) {
74            type Primitive = ($t0::Primitive, $( $ty::Primitive ),*);
75
76            #[inline]
77            fn new(mode: Mode, value: Self::Primitive) -> Self {
78                ($t0::new(mode, value.0), $($ty::new(mode, value.$idx)),*)
79            }
80        }
81    }
82}
83
84inject_tuple!((C0, 0), (C1, 1));
85inject_tuple!((C0, 0), (C1, 1), (C2, 2));
86inject_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3));
87inject_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3), (C4, 4));