Skip to content

Commit de9b660

Browse files
committed
Explain why pointer::add in slice::as_ptr_range is safe.
1 parent f1b69b0 commit de9b660

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/libcore/slice/mod.rs

+18
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,23 @@ impl<T> [T] {
437437
#[unstable(feature = "slice_ptr_range", issue = "65807")]
438438
#[inline]
439439
pub fn as_ptr_range(&self) -> Range<*const T> {
440+
// The `add` here is safe, because:
441+
//
442+
// - Both pointers are part of the same object, as pointing directly
443+
// past the object also counts.
444+
//
445+
// - The size of the slice is never larger than isize::MAX bytes, as
446+
// noted here:
447+
// - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
448+
// - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
449+
// - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
450+
// (This doesn't seem normative yet, but the very same assumption is
451+
// made in many places, including the Index implementation of slices.)
452+
//
453+
// - There is no wrapping around involved, as slices do not wrap past
454+
// the end of the address space.
455+
//
456+
// See the documentation of pointer::add.
440457
let start = self.as_ptr();
441458
let end = unsafe { start.add(self.len()) };
442459
start..end
@@ -461,6 +478,7 @@ impl<T> [T] {
461478
#[unstable(feature = "slice_ptr_range", issue = "65807")]
462479
#[inline]
463480
pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
481+
// See as_ptr_range() above for why `add` here is safe.
464482
let start = self.as_mut_ptr();
465483
let end = unsafe { start.add(self.len()) };
466484
start..end

0 commit comments

Comments
 (0)