Re: [PATCH v3 1/2] rust: kernel: create `overflow_assert!` macro

From: Tamir Duberstein
Date: Sun Jun 22 2025 - 18:54:14 EST


On Sun, Jun 22, 2025 at 6:20 PM Antonio Hickey
<contact@xxxxxxxxxxxxxxxxx> wrote:
>
> On Sun 22 Jun 13:48, Tamir Duberstein wrote:
> > On Sat, Jun 21, 2025 at 7:06 PM Antonio Hickey
> > <contact@xxxxxxxxxxxxxxxxx> wrote:
> > > +//! Overflow assert.
> >
> > s/assert/assertion/
> >
> > AFAIK the standard library always uses assertion where a noun is
> > needed, and assert where a verb is needed.
> >
>
> Reasonable, I'll fix this verbage in my next version.
>
> > > +/// Verifies at runtime that an expression is within an expected bound.
> > > +///
> > > +/// This macro is only active when `CONFIG_RUST_OVERFLOW_CHECKS` is enabled.
> > > +///
> > > +/// # Examples
> > > +///
> > > +/// ```
> > > +/// overflow_assert!(3 <= 10);
> > > +/// overflow_assert!(5 <= 5);
> > > +///
> > > +/// const X: u8 = 5;
> > > +/// overflow_assert!(X + 3 < 10);
> > > +///
> > > +/// const fn f(x: i32) -> i32 {
> > > +/// x + 1
> > > +/// }
> > > +/// overflow_assert!(f(40) < 42);
> > > +/// ```
> > > +#[macro_export]
> > > +macro_rules! overflow_assert {
> > > + ($cond:expr) => {
> > > + if cfg!(CONFIG_RUST_OVERFLOW_CHECKS) {
> > > + ::core::assert!(
> > > + $cond,
> > > + concat!("overflow assertion failed: ", stringify!($cond))
> >
> > Can we still allow the caller to pass additional arguments to the
> > macro, so that the overflowing value can be emitted? Alternatively if
> > the expectation is that this macro is always used with a comparison
> > operator perhaps we could have `overflow_assert_lt` and
> > `overflow_assert_le` which provide panic messages containing the
> > operand values?
> >
>
> Me and Miguel discussed the `overflow_assert_le` and other variants in
> my previous v2 patch set[1]. We decided it would be best to just start
> with a more flexable general expression based variant of the macro for
> now, and consider other variants later.
>
> I agree we should expand this into more specific variants, so it would
> document the intent of the assertions even more clearly.
>
> [1] Link to Miguel's comment on a `overflow_assert_le` variant:
> https://lore.kernel.org/all/CANiq72mvu54B=U+YCUmbFctj_wXgF5zjeE-BB-vHVnAP+3mPcQ@xxxxxxxxxxxxxx/

Ack, thanks for that. Still, I think the "any expression" version
should allow the caller to supply a custom message.