Re: [PATCH v6] rust: kernel: add support for bits/genmask macros

From: Alexandre Courbot
Date: Mon Jun 16 2025 - 11:09:53 EST


On Mon Jun 16, 2025 at 11:14 PM JST, Daniel Almeida wrote:
>>> +macro_rules! impl_bit_fn {
>>> + (
>>> + $checked_name:ident, $unbounded_name:ident, $const_name:ident, $ty:ty
>>> + ) => {
>>> + /// Computes `1 << n` if `n` is in bounds, i.e.: if `n` is smaller than
>>> + /// the maximum number of bits supported by the type.
>>> + ///
>>> + /// Returns [`None`] otherwise.
>>> + #[inline]
>>> + pub fn $checked_name(n: u32) -> Option<$ty> {
>>> + (1 as $ty) .checked_shl(n)
>>> + }
>>> +
>>> + /// Computes `1 << n` if `n` is in bounds, i.e.: if `n` is smaller than
>>> + /// the maximum number of bits supported by the type.
>>> + ///
>>> + /// Returns `0` otherwise.
>>> + ///
>>> + /// This is a convenience, as [`Option::unwrap_or`] cannot be used in
>>> + /// const-context.
>>> + #[inline]
>>> + pub fn $unbounded_name(n: u32) -> $ty {
>>> + match $checked_name(n) {
>>> + Some(v) => v,
>>> + None => 0,
>>> + }
>>
>> This could more succintly be `$checked_name(n).unwrap_or(0)` (same
>> remark for `$genmask_unbounded` below).
>>
>
> Wait, I just realized that $unbounded_name is not ‘const fn’, so we don’t need this function at all?
>
> Users can simply do `unwrap_or` on their own.

Agreed, we can probably drop this.

>>
>> ... or we make the methods generic against `RangeBounds` and allow both
>> `Range` and `RangeInclusive` to be used. But I'm concerned that callers
>> might use `0..1` thinking it is inclusive while it is not.
>>
>> Thoughts?
>
> I don't think we can do what you suggested here. I assume that we'd have to
> rely on [0] and friends, and these are not const fn, so they can’t be used in
> the const version of genmask.

You are right, this cannot be used here. It's not a big loss, limiting
the API to inclusive ranges as discussed on the other thread might
actually end up being safer than having two options.