Skip to content

Commit fb08915

Browse files
committed
clarify offset function safety concerns
1 parent a2af866 commit fb08915

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/libcore/ptr.rs

+16-4
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,7 @@ impl<T: ?Sized> *const T {
591591
/// Behavior:
592592
///
593593
/// * Both the starting and resulting pointer must be either in bounds or one
594-
/// byte past the end of an allocated object.
594+
/// byte past the end of *the same* allocated object.
595595
///
596596
/// * The computed offset, **in bytes**, cannot overflow an `isize`.
597597
///
@@ -643,9 +643,15 @@ impl<T: ?Sized> *const T {
643643
///
644644
/// The resulting pointer does not need to be in bounds, but it is
645645
/// potentially hazardous to dereference (which requires `unsafe`).
646+
/// In particular, the resulting pointer may *not* be used to access a
647+
/// different allocated object than the one `self` points to. In other
648+
/// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
649+
/// *not* the same as `y`, and dereferencing it is undefined behavior
650+
/// unless `x` and `y` point into the same allocated object.
646651
///
647652
/// Always use `.offset(count)` instead when possible, because `offset`
648-
/// allows the compiler to optimize better.
653+
/// allows the compiler to optimize better. If you need to cross object
654+
/// boundaries, cast the pointer to an integer and do the arithmetic there.
649655
///
650656
/// # Examples
651657
///
@@ -1340,7 +1346,7 @@ impl<T: ?Sized> *mut T {
13401346
/// Behavior:
13411347
///
13421348
/// * Both the starting and resulting pointer must be either in bounds or one
1343-
/// byte past the end of an allocated object.
1349+
/// byte past the end of *the same* allocated object.
13441350
///
13451351
/// * The computed offset, **in bytes**, cannot overflow an `isize`.
13461352
///
@@ -1391,9 +1397,15 @@ impl<T: ?Sized> *mut T {
13911397
///
13921398
/// The resulting pointer does not need to be in bounds, but it is
13931399
/// potentially hazardous to dereference (which requires `unsafe`).
1400+
/// In particular, the resulting pointer may *not* be used to access a
1401+
/// different allocated object than the one `self` points to. In other
1402+
/// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1403+
/// *not* the same as `y`, and dereferencing it is undefined behavior
1404+
/// unless `x` and `y` point into the same allocated object.
13941405
///
13951406
/// Always use `.offset(count)` instead when possible, because `offset`
1396-
/// allows the compiler to optimize better.
1407+
/// allows the compiler to optimize better. If you need to cross object
1408+
/// boundaries, cast the pointer to an integer and do the arithmetic there.
13971409
///
13981410
/// # Examples
13991411
///

0 commit comments

Comments
 (0)