Skip to content

Commit 0794302

Browse files
committed
Explain one-past-the-end pointer in std library
Signed-off-by: xizheyin <[email protected]>
1 parent ae8ab87 commit 0794302

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed

library/core/src/ptr/const_ptr.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,12 @@ impl<T: ?Sized> *const T {
388388
/// bounds of that allocated object. In particular, this range must not "wrap around" the edge
389389
/// of the address space.
390390
///
391+
/// * Note that the special case of "one-past-the-end" pointers is explicitly allowed: a pointer
392+
/// exactly one byte past the end of an allocated object (at address `base + size`, using the
393+
/// terminology from [allocated object]) is valid for offset calculations, though dereferencing
394+
/// such a pointer remains invalid. This allows for efficiently calculating ranges and detecting
395+
/// the end of iteration.
396+
///
391397
/// Allocated objects can never be larger than `isize::MAX` bytes, so if the computed offset
392398
/// stays in bounds of the allocated object, it is guaranteed to satisfy the first requirement.
393399
/// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always

library/core/src/ptr/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,9 @@
116116
//! `addresses`, the following are guaranteed:
117117
//! - For all addresses `a` in `addresses`, `a` is in the range `base .. (base +
118118
//! size)` (note that this requires `a < base + size`, not `a <= base + size`)
119+
//! - However, for pointer offset calculations, a special "one-past-the-end" address
120+
//! exactly at `base + size` is considered valid, though this address may not be
121+
//! dereferenced. This exception is crucial for iteration and range calculations.
119122
//! - `base` is not equal to [`null()`] (i.e., the address with the numerical
120123
//! value 0)
121124
//! - `base + size <= usize::MAX`

0 commit comments

Comments
 (0)