[PATCH v2 1/2] rust: impl_flags: add conversion functions
From: Andreas Hindborg
Date: Fri Jun 05 2026 - 09:06:22 EST
Add two conversion functions to the `impl_flags!` macro:
- A `From<_>` implementation to convert from the flag value enum to
underlying type.
- A `TryFrom<_> implementation to convert from the underlying
representation to flag container type.
Signed-off-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
---
rust/kernel/impl_flags.rs | 31 +++++++++++++++++++++++++++++++
1 file changed, 31 insertions(+)
diff --git a/rust/kernel/impl_flags.rs b/rust/kernel/impl_flags.rs
index 1d39d54540dc..04a4b0a356df 100644
--- a/rust/kernel/impl_flags.rs
+++ b/rust/kernel/impl_flags.rs
@@ -77,6 +77,17 @@
/// // representation — useful for passing the value to a C API.
/// let raw: u32 = read_only.bits();
/// assert_eq!(raw, Permission::Read as u32);
+///
+/// // Convert a single flag value to its underlying integer representation.
+/// let raw_read: u32 = Permission::Read.into();
+/// assert_eq!(raw_read, Permission::Read as u32);
+///
+/// // Construct a `Permissions` value from a raw integer. `TryFrom` rejects
+/// // integers whose set bits do not all correspond to declared flags.
+/// let parsed = Permissions::try_from(raw_read | Permission::Write as u32).unwrap();
+/// assert!(parsed.contains(Permission::Read));
+/// assert!(parsed.contains(Permission::Write));
+/// assert!(Permissions::try_from(1 << 7).is_err());
/// ```
#[macro_export]
macro_rules! impl_flags {
@@ -119,6 +130,26 @@ fn from(value: $flags) -> Self {
}
}
+ impl ::core::convert::From<$flag> for $ty {
+ #[inline]
+ fn from(value: $flag) -> Self {
+ value as Self
+ }
+ }
+
+ impl ::core::convert::TryFrom<$ty> for $flags {
+ type Error = ::kernel::error::Error;
+
+ #[inline]
+ fn try_from(value: $ty) -> Result<Self, Self::Error> {
+ if value & !$flags::all_bits() != 0 {
+ return Err(::kernel::error::code::EINVAL);
+ }
+
+ Ok(Self(value))
+ }
+ }
+
impl ::core::ops::BitOr for $flags {
type Output = Self;
#[inline]
--
2.51.2