]> www.infradead.org Git - users/jedix/linux-maple.git/commitdiff
rust: pin-init: add `zeroed()` & `Zeroable::zeroed()` functions
authorBenno Lossin <lossin@kernel.org>
Fri, 23 May 2025 14:50:59 +0000 (16:50 +0200)
committerBenno Lossin <lossin@kernel.org>
Wed, 11 Jun 2025 19:13:56 +0000 (21:13 +0200)
`zeroed()` returns a zeroed out value of a sized type implementing
`Zeroable`.

The function is added as a free standing function, in addition to an
associated function on `Zeroable`, because then it can be marked `const`
(functions in traits can't be const at the moment).

Link: https://github.com/Rust-for-Linux/pin-init/pull/56/commits/809e4ec160579c1601dce5d78b432a5b6c8e4e40
Link: https://lore.kernel.org/all/20250523145125.523275-4-lossin@kernel.org
Signed-off-by: Benno Lossin <lossin@kernel.org>
rust/pin-init/src/lib.rs

index ef7e5a1e1c48eae2a0bec30a4dfa830e5a8bd38a..a5bb3939b58b4caec2c5a1c848eaa07de08cc0d9 100644 (file)
@@ -1506,6 +1506,33 @@ pub unsafe trait Zeroable {
     {
         init_zeroed()
     }
+
+    /// Create a `Self` consisting of all zeroes.
+    ///
+    /// Whenever a type implements [`Zeroable`], this function should be preferred over
+    /// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use pin_init::{Zeroable, zeroed};
+    ///
+    /// #[derive(Zeroable)]
+    /// struct Point {
+    ///     x: u32,
+    ///     y: u32,
+    /// }
+    ///
+    /// let point: Point = zeroed();
+    /// assert_eq!(point.x, 0);
+    /// assert_eq!(point.y, 0);
+    /// ```
+    fn zeroed() -> Self
+    where
+        Self: Sized,
+    {
+        zeroed()
+    }
 }
 
 /// Marker trait for types that allow `Option<Self>` to be set to all zeroes in order to write
@@ -1534,6 +1561,31 @@ pub fn init_zeroed<T: Zeroable>() -> impl Init<T> {
     }
 }
 
+/// Create a `T` consisting of all zeroes.
+///
+/// Whenever a type implements [`Zeroable`], this function should be preferred over
+/// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`.
+///
+/// # Examples
+///
+/// ```
+/// use pin_init::{Zeroable, zeroed};
+///
+/// #[derive(Zeroable)]
+/// struct Point {
+///     x: u32,
+///     y: u32,
+/// }
+///
+/// let point: Point = zeroed();
+/// assert_eq!(point.x, 0);
+/// assert_eq!(point.y, 0);
+/// ```
+pub const fn zeroed<T: Zeroable>() -> T {
+    // SAFETY:By the type invariants of `Zeroable`, all zeroes is a valid bit pattern for `T`.
+    unsafe { core::mem::zeroed() }
+}
+
 macro_rules! impl_zeroable {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
         // SAFETY: Safety comments written in the macro invocation.