Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion library/core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,11 @@ impl<T: PointeeSized> *const T {
let pointee_size = size_of::<T>();
assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
// SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
let offset = unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) };
// SAFETY: the safety contract guarantees that the pointers differ by at most
// `isize::MAX` bytes, so the result cannot be larger than `isize::MAX` elements.
unsafe { intrinsics::assume(offset <= isize::MAX as usize) };
offset
}

/// Calculates the distance between two pointers within the same allocation, *where it's known that
Expand Down
10 changes: 10 additions & 0 deletions tests/codegen-llvm/intrinsics/offset_from.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//! Basic optimizations are enabled because otherwise `x86_64-gnu-nopt` had an alloca.
//! Uses a type with non-power-of-two size to avoid normalizations to shifts.

use std::convert::TryFrom;
use std::intrinsics::*;

type RGB = [u8; 3];
Expand Down Expand Up @@ -34,3 +35,12 @@ pub unsafe fn offset_from_unsigned_odd_size(a: *const RGB, b: *const RGB) -> usi
// CHECK-NEXT: ret i64
ptr_offset_from_unsigned(a, b)
}

// CHECK-LABEL: @offset_from_unsigned_u8_fits_isize
#[no_mangle]
pub unsafe fn offset_from_unsigned_u8_fits_isize(a: *const u8, b: *const u8) -> isize {
// CHECK-NOT: unwrap_failed
// CHECK-NOT: br i1
// CHECK: ret i64
isize::try_from(a.offset_from_unsigned(b)).unwrap()
}
Loading