openvm_circuit_primitives/var_range/
bus.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use openvm_stark_backend::{
    interaction::{InteractionBuilder, InteractionType},
    p3_field::AbstractField,
};

// Represents a bus for (x, bits) where either (x, bits) = (0, 0) or
// x is in [0, 2^bits) and bits is in [1, range_max_bits]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VariableRangeCheckerBus {
    pub index: usize,
    pub range_max_bits: usize,
}

impl VariableRangeCheckerBus {
    pub const fn new(index: usize, range_max_bits: usize) -> Self {
        Self {
            index,
            range_max_bits,
        }
    }

    #[must_use]
    pub fn send<T>(
        &self,
        value: impl Into<T>,
        max_bits: impl Into<T>,
    ) -> VariableRangeCheckerBusInteraction<T> {
        self.push(value, max_bits, InteractionType::Send)
    }

    #[must_use]
    pub fn receive<T>(
        &self,
        value: impl Into<T>,
        max_bits: impl Into<T>,
    ) -> VariableRangeCheckerBusInteraction<T> {
        self.push(value, max_bits, InteractionType::Receive)
    }

    // Equivalent to `self.send(value, max_bits)` where max_bits is a usize constant
    #[must_use]
    pub fn range_check<T>(
        &self,
        value: impl Into<T>,
        max_bits: usize,
    ) -> VariableRangeCheckerBusInteraction<T>
    where
        T: AbstractField,
    {
        debug_assert!(max_bits <= self.range_max_bits);
        self.push(
            value,
            T::from_canonical_usize(max_bits),
            InteractionType::Send,
        )
    }

    pub fn push<T>(
        &self,
        value: impl Into<T>,
        max_bits: impl Into<T>,
        interaction_type: InteractionType,
    ) -> VariableRangeCheckerBusInteraction<T> {
        VariableRangeCheckerBusInteraction {
            value: value.into(),
            max_bits: max_bits.into(),
            bus_index: self.index,
            interaction_type,
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub struct VariableRangeCheckerBusInteraction<T> {
    pub value: T,
    pub max_bits: T,
    pub bus_index: usize,
    pub interaction_type: InteractionType,
}

impl<T: AbstractField> VariableRangeCheckerBusInteraction<T> {
    pub fn eval<AB>(self, builder: &mut AB, count: impl Into<AB::Expr>)
    where
        AB: InteractionBuilder<Expr = T>,
    {
        builder.push_interaction(
            self.bus_index,
            [self.value, self.max_bits],
            count,
            self.interaction_type,
        );
    }
}