bump_scope/polyfill/
pointer.rs

1use core::{hint, mem, ptr};
2
3/// See `<*const T>::offset_from_unsigned`.
4#[inline]
5#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
6#[expect(clippy::cast_sign_loss)]
7#[expect(clippy::checked_conversions)]
8pub(crate) unsafe fn offset_from_unsigned<T>(this: *const T, origin: *const T) -> usize {
9    unsafe {
10        hint::assert_unchecked(this >= origin);
11        let pointee_size = mem::size_of::<T>();
12        assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
13        this.offset_from(origin) as usize
14    }
15}
16
17/// Not part of std.
18///
19/// Putting the expression in a function helps llvm to realize that it can initialize the value
20/// at this pointer instead of allocating it on the stack and then copying it over.
21#[inline(always)]
22pub(crate) unsafe fn write_with<T>(ptr: *mut T, f: impl FnOnce() -> T) {
23    unsafe { ptr::write(ptr, f()) };
24}