[PATCH 02/10] rust: Add an Integer trait

Remo Senekowitsch
2025-03-26T17:23:25Z

From: "Rob Herring (Arm)" <robh@kernel.org>

Add an "Integer" trait similar to crate::num::Integer. This is useful
for implementing generic methods which operate on different sizes of
integers. One example is reading DT/ACPI firmware properties.

This was originally proposed by Alice Ryhl[1].

[1] https://lore.kernel.org/rust-for-linux/CAH5fLgiXPZqKpWSSNdx-Ww-E9h2tOLcF3_8Y4C_JQ0eU8EMwFw@mail.gmail.com/

Suggested-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Rob Herring (Arm) <robh@kernel.org>
---
rust/kernel/types.rs | 22 +++++++++++++++++++++-
1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs
index 2bbaab83b..21647b7ba 100644
--- a/rust/kernel/types.rs
+++ b/rust/kernel/types.rs
@@ -3,10 +3,11 @@
//! Kernel types.

use crate::init::{self, PinInit};
+use crate::transmute::{AsBytes, FromBytes};
use core::{
cell::UnsafeCell,
marker::{PhantomData, PhantomPinned},
- mem::{ManuallyDrop, MaybeUninit},
+ mem::{size_of, ManuallyDrop, MaybeUninit},
ops::{Deref, DerefMut},
ptr::NonNull,
};
@@ -553,6 +554,25 @@ pub enum Either<L, R> {
Right(R),
}

+/// Trait defined for all integer types similar to `crate::num::Integer`
+pub trait Integer: FromBytes + AsBytes + Copy {
+ /// Size of the integer in bytes
+ const SIZE: usize;
+}
+
+macro_rules! impl_int {
+ ($($typ:ty),* $(,)?) => {$(
+ impl Integer for $typ {
+ const SIZE: usize = size_of::<Self>();
+ }
+ )*};
+}
+
+impl_int! {
+ u8, u16, u32, u64, usize,
+ i8, i16, i32, i64, isize,
+}
+
/// Zero-sized type to mark types not [`Send`].
///
/// Add this type as a field to your struct if your type should not be sent to a different task.
--
2.49.0