Add a few convenience functions that makes it easier to work with the
`impl_flags` module and C APIs.
These conversion functions are useful when assigning flags to C structs in
Rust abstractions:
let mut lim = bindings::queue_limits::zeroed();
if self.rotational {
lim.features = Feature::Rotational.into();
}
if self.write_cache {
lim.features |= Feature::WriteCache;
}
Or when providing flags from C to Rust:
impl<T: Operations> RequestInner<T> {
pub fn flags(&self) -> Flags {
// SAFETY: By C API contract and type invariant, `cmd_flags` is valid for read
let flags = unsafe { (*self.0.get()).cmd_flags & !((1 << bindings::REQ_OP_BITS) - 1) };
Flags::try_from(flags).expect("Request should have valid falgs")
}
}
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
Changes in v2:
- Use an `as` cast instead of `core::mem::transmute` in
`From<$flag> for $ty` (Miguel).
- Replace the `match` in `TryFrom::try_from` with an early-return
`if` (Miguel)
- Construct the result directly instead of via `transmute` in `try_from`
(Miguel).
- Use `Self` in the new conversion impls (Miguel).
- Mark `TryFrom::try_from` `#[inline]`.
- Extend the rustdoc example to demonstrate both new conversion
impls (Miguel).
- Link to v1: https://msgid.link/20260215-impl-flags-additions-v1-0-6538c8fb841c@kernel.org
To: Miguel Ojeda <ojeda@kernel.org>
To: Boqun Feng <boqun@kernel.org>
To: Gary Guo <gary@garyguo.net>
To: Björn Roy Baron <bjorn3_gh@protonmail.com>
To: Benno Lossin <lossin@kernel.org>
To: Andreas Hindborg <a.hindborg@kernel.org>
To: Alice Ryhl <aliceryhl@google.com>
To: Trevor Gross <tmgross@umich.edu>
To: Danilo Krummrich <dakr@kernel.org>
Cc: rust-for-linux@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
---
Andreas Hindborg (2):
rust: impl_flags: add conversion functions
rust: impl_flags: add bitwise operations with the underlying type
rust/kernel/impl_flags.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 47 insertions(+)
---
base-commit: 9e0898f1c0f134c6bad146ca8578f73c3e40ac0a
change-id: 20260215-impl-flags-additions-0340ffcba5b9
prerequisite-change-id: 20260212-impl-flags-inner-c61974b27b18:v2
prerequisite-patch-id: 379fb78c07b554278fae3c42d84d62bcfcfa0d45
Best regards,
--
Andreas Hindborg <a.hindborg@kernel.org>