halo2_base/safe_types/
primitives.rs

1use std::ops::Deref;
2
3use crate::QuantumCell;
4
5use super::*;
6/// SafeType for bool (1 bit).
7///
8/// This is a separate struct from `CompactSafeType` with the same behavior. Because
9/// we know only one [`AssignedValue`] is needed to hold the boolean value, we avoid
10/// using `CompactSafeType` to avoid the additional heap allocation from a length 1 vector.
11#[derive(Clone, Copy, Debug)]
12pub struct SafeBool<F: ScalarField>(pub(super) AssignedValue<F>);
13
14/// SafeType for byte (8 bits).
15///
16/// This is a separate struct from `CompactSafeType` with the same behavior. Because
17/// we know only one [`AssignedValue`] is needed to hold the boolean value, we avoid
18/// using `CompactSafeType` to avoid the additional heap allocation from a length 1 vector.
19#[derive(Clone, Copy, Debug)]
20pub struct SafeByte<F: ScalarField>(pub(super) AssignedValue<F>);
21
22macro_rules! safe_primitive_impls {
23    ($SafePrimitive:ty) => {
24        impl<F: ScalarField> AsRef<AssignedValue<F>> for $SafePrimitive {
25            fn as_ref(&self) -> &AssignedValue<F> {
26                &self.0
27            }
28        }
29
30        impl<F: ScalarField> Borrow<AssignedValue<F>> for $SafePrimitive {
31            fn borrow(&self) -> &AssignedValue<F> {
32                &self.0
33            }
34        }
35
36        impl<F: ScalarField> Deref for $SafePrimitive {
37            type Target = AssignedValue<F>;
38
39            fn deref(&self) -> &Self::Target {
40                &self.0
41            }
42        }
43
44        impl<F: ScalarField> From<$SafePrimitive> for AssignedValue<F> {
45            fn from(safe_primitive: $SafePrimitive) -> Self {
46                safe_primitive.0
47            }
48        }
49
50        impl<F: ScalarField> From<$SafePrimitive> for QuantumCell<F> {
51            fn from(safe_primitive: $SafePrimitive) -> Self {
52                QuantumCell::Existing(safe_primitive.0)
53            }
54        }
55    };
56}
57
58safe_primitive_impls!(SafeBool<F>);
59safe_primitive_impls!(SafeByte<F>);