use openvm_stark_backend::{
interaction::{BusIndex, InteractionBuilder, LookupBus},
p3_field::{PrimeCharacteristicRing, PrimeField32},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RangeCheckBus {
pub inner: LookupBus,
pub range_max: u32,
}
impl RangeCheckBus {
pub const fn new(index: BusIndex, range_max: u32) -> Self {
Self {
inner: LookupBus::new(index),
range_max,
}
}
pub fn range_check<R: PrimeCharacteristicRing>(
&self,
x: impl Into<R>,
max_bits: usize,
) -> BitsCheckBusInteraction<R>
where
R::PrimeSubfield: PrimeField32,
{
debug_assert!((1 << max_bits) <= self.range_max);
debug_assert!(self.range_max < R::PrimeSubfield::ORDER_U32 / 2);
let shift = self.range_max - (1 << max_bits);
BitsCheckBusInteraction {
x: x.into(),
shift,
bus: self.inner,
}
}
pub fn send<T>(&self, x: impl Into<T>) -> RangeCheckBusInteraction<T> {
self.push(x, true)
}
pub fn receive<T>(&self, x: impl Into<T>) -> RangeCheckBusInteraction<T> {
self.push(x, false)
}
pub fn push<T>(&self, x: impl Into<T>, is_lookup: bool) -> RangeCheckBusInteraction<T> {
RangeCheckBusInteraction {
x: x.into(),
bus: self.inner,
is_lookup,
}
}
pub fn index(&self) -> BusIndex {
self.inner.index
}
}
#[derive(Clone, Copy, Debug)]
pub struct BitsCheckBusInteraction<T> {
pub x: T,
pub shift: u32,
pub bus: LookupBus,
}
#[derive(Clone, Copy, Debug)]
pub struct RangeCheckBusInteraction<T> {
pub x: T,
pub bus: LookupBus,
pub is_lookup: bool,
}
impl<T: PrimeCharacteristicRing> RangeCheckBusInteraction<T> {
pub fn eval<AB>(self, builder: &mut AB, count: impl Into<AB::Expr>)
where
AB: InteractionBuilder<Expr = T>,
{
if self.is_lookup {
self.bus.lookup_key(builder, [self.x], count);
} else {
self.bus.add_key_with_lookups(builder, [self.x], count);
}
}
}
impl<T: PrimeCharacteristicRing> BitsCheckBusInteraction<T> {
pub fn eval<AB>(self, builder: &mut AB, count: impl Into<AB::Expr>)
where
AB: InteractionBuilder<Expr = T>,
{
let count = count.into();
if self.shift > 0 {
self.bus.lookup_key(
builder,
[self.x.clone() + AB::Expr::from_u32(self.shift)],
count.clone(),
);
}
self.bus.lookup_key(builder, [self.x], count);
}
}