[PATCH v3 2/2] rust: impl_flags: add bitwise operations with the underlying type

From: Andreas Hindborg

Date: Thu Nov 05 2026 - 11:21:50 EST


Add bitwise or operations between the flag value enum and the underlying
type, so a flag value can be combined directly into an integer field of a C
struct.

Rust abstractions that configure a C struct assign to a raw integer field,
often conditionally and from more than one place. The upcoming
`block::mq::gen_disk` conversion declares a `Feature` enum with
`impl_flags!` and folds individual flags into `queue_limits::features`.
With only the `From` implementation from the previous patch, that reads:

let mut lim: bindings::queue_limits = pin_init::zeroed();

if self.rotational {
lim.features = Feature::Rotational.into();
}

#[cfg(CONFIG_BLK_DEV_ZONED)]
if self.zoned {
lim.features |= u32::from(Feature::Zoned);
}

if self.write_cache {
lim.features |= u32::from(Feature::WriteCache);
}

With this patch:

let mut lim: bindings::queue_limits = pin_init::zeroed();

if self.rotational {
lim.features = Feature::Rotational.into();
}

#[cfg(CONFIG_BLK_DEV_ZONED)]
if self.zoned {
lim.features |= Feature::Zoned;
}

if self.write_cache {
lim.features |= Feature::WriteCache;
}

Note the asymmetry of the first assignment to the rest. The plain
assignment can be written `Feature::Rotational.into()`, but the compound
assignments cannot use `.into()`: `u32` implements both `BitOrAssign<u32>`
and `BitOrAssign<&u32>`, so the target type of `.into()` is ambiguous and
inference fails with E0283. Without these implementations, every compound
assignment has to name the underlying type explicitly.

An `as` cast is one way around that, but we try to avoid casts, and unlike
`u32::from` it would keep compiling silently if the field type were
widened.

The other option is a container temporary: accumulate into a `Features`
value using the operators the macro already generates, then assign
`features.bits()` to the field at the end. This requires a new temporary
per flag field we want to assign and clutters the code.

Signed-off-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
---
rust/kernel/impl_flags.rs | 16 ++++++++++++++++
1 file changed, 16 insertions(+)

diff --git a/rust/kernel/impl_flags.rs b/rust/kernel/impl_flags.rs
index 052759b8038d..53f6ba5d5952 100644
--- a/rust/kernel/impl_flags.rs
+++ b/rust/kernel/impl_flags.rs
@@ -276,6 +276,22 @@ fn not(self) -> Self::Output {
}
}

+ impl ::core::ops::BitOr<$flag> for $ty {
+ type Output = Self;
+
+ #[inline]
+ fn bitor(self, rhs: $flag) -> Self::Output {
+ self | <$flag as Into<Self>>::into(rhs)
+ }
+ }
+
+ impl ::core::ops::BitOrAssign<$flag> for $ty {
+ #[inline]
+ fn bitor_assign(&mut self, rhs: $flag) {
+ *self = *self | <$flag as Into<Self>>::into(rhs)
+ }
+ }
+
impl $flags {
/// Returns an empty instance where no flags are set.
#[inline]

--
2.54.0