Skip to content

Commit 1293d44

Browse files
committed
add cast_[pin_]init functions to change the initialized type
These functions cast the given pointer from one type to another. They are particularly useful when initializing transparent wrapper types. Signed-off-by: Benno Lossin <benno.lossin@proton.me>
1 parent fc6169f commit 1293d44

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

src/lib.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1216,6 +1216,36 @@ pub const unsafe fn init_from_closure<T: ?Sized, E>(
12161216
__internal::InitClosure(f, PhantomData)
12171217
}
12181218

1219+
/// Changes the to be initialized type.
1220+
///
1221+
/// # Safety
1222+
///
1223+
/// - `T` must be castable to `U`
1224+
#[expect(clippy::let_and_return)]
1225+
pub const unsafe fn cast_pin_init<T, U, E>(init: impl PinInit<T, E>) -> impl PinInit<U, E> {
1226+
// SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1227+
// requirements.
1228+
let res = unsafe { pin_init_from_closure(|ptr: *mut U| init.__pinned_init(ptr.cast::<T>())) };
1229+
// FIXME: remove the let statement once the nightly-MSRV allows it (1.78 otherwise encounters a
1230+
// cycle when computing the type returned by this function)
1231+
res
1232+
}
1233+
1234+
/// Changes the to be initialized type.
1235+
///
1236+
/// # Safety
1237+
///
1238+
/// - `T` must be castable to `U`
1239+
#[expect(clippy::let_and_return)]
1240+
pub const unsafe fn cast_init<T, U, E>(init: impl Init<T, E>) -> impl Init<U, E> {
1241+
// SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1242+
// requirements.
1243+
let res = unsafe { init_from_closure(|ptr: *mut U| init.__init(ptr.cast::<T>())) };
1244+
// FIXME: remove the let statement once the nightly-MSRV allows it (1.78 otherwise encounters a
1245+
// cycle when computing the type returned by this function)
1246+
res
1247+
}
1248+
12191249
/// An initializer that leaves the memory uninitialized.
12201250
///
12211251
/// The initializer is a no-op. The `slot` memory is not changed.

0 commit comments

Comments
 (0)