Skip to content

Commit fd1d8a9

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 fd1d8a9

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

src/lib.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1216,6 +1216,28 @@ 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+
pub const unsafe fn cast_pin_init<T, U, E>(init: impl PinInit<T, E>) -> impl PinInit<U, E> {
1225+
// SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1226+
// requirements.
1227+
unsafe { pin_init_from_closure(|ptr: *mut U| init.__pinned_init(ptr.cast::<T>())) }
1228+
}
1229+
1230+
/// Changes the to be initialized type.
1231+
///
1232+
/// # Safety
1233+
///
1234+
/// - `T` must be castable to `U`
1235+
pub const unsafe fn cast_init<T, U, E>(init: impl Init<T, E>) -> impl Init<U, E> {
1236+
// SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1237+
// requirements.
1238+
unsafe { init_from_closure(|ptr: *mut U| init.__init(ptr.cast::<T>())) }
1239+
}
1240+
12191241
/// An initializer that leaves the memory uninitialized.
12201242
///
12211243
/// The initializer is a no-op. The `slot` memory is not changed.

0 commit comments

Comments
 (0)