Skip to content

Commit c349daa

Browse files
hoshinolinajannau
authored andcommitted
rust: init: Add default() utility function
Initializer for types with Default::default() implementations in init context. This, by nature, only works for types which are not pinned. Signed-off-by: Asahi Lina <lina@asahilina.net>
1 parent 8d0d979 commit c349daa

1 file changed

Lines changed: 15 additions & 0 deletions

File tree

rust/pin-init/src/lib.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1574,6 +1574,21 @@ pub unsafe trait PinnedDrop: __internal::HasPinData {
15741574
fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop);
15751575
}
15761576

1577+
/// Create a new default T.
1578+
///
1579+
/// The returned initializer will use Default::default to initialize the `slot`.
1580+
#[inline]
1581+
pub fn default<T: Default>() -> impl Init<T> {
1582+
// SAFETY: Because `T: Default`, T cannot require pinning and
1583+
// we can just move the data into the slot.
1584+
unsafe {
1585+
init_from_closure(|slot: *mut T| {
1586+
*slot = Default::default();
1587+
Ok(())
1588+
})
1589+
}
1590+
}
1591+
15771592
/// Marker trait for types that can be initialized by writing just zeroes.
15781593
///
15791594
/// # Safety

0 commit comments

Comments
 (0)