Skip to content

Commit c0f86f5

Browse files
committed
Auto merge of #41602 - hsivonen:explainnonnull, r=steveklabnik
Explain why zero-length slices require a non-null pointer In reference to [a thread on Discourse](https://users.rust-lang.org/t/why-does-std-slice-from-raw-parts-require-a-non-null-pointer-for-zero-length-slices/10534), explain why `from_raw_parts` requires a non-null pointer for zero-length slices. r? @steveklabnik
2 parents 78f6318 + e36f59e commit c0f86f5

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

src/libcore/slice/mod.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -2354,7 +2354,10 @@ impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
23542354
/// valid for `len` elements, nor whether the lifetime inferred is a suitable
23552355
/// lifetime for the returned slice.
23562356
///
2357-
/// `p` must be non-null, even for zero-length slices.
2357+
/// `p` must be non-null, even for zero-length slices, because non-zero bits
2358+
/// are required to distinguish between a zero-length slice within `Some()`
2359+
/// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
2360+
/// for zero-length slices, though.
23582361
///
23592362
/// # Caveat
23602363
///
@@ -2387,7 +2390,8 @@ pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
23872390
///
23882391
/// This function is unsafe for the same reasons as `from_raw_parts`, as well
23892392
/// as not being able to provide a non-aliasing guarantee of the returned
2390-
/// mutable slice.
2393+
/// mutable slice. `p` must be non-null even for zero-length slices as with
2394+
/// `from_raw_parts`.
23912395
#[inline]
23922396
#[stable(feature = "rust1", since = "1.0.0")]
23932397
pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {

src/libcore/str/mod.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,10 @@ pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
319319
///
320320
/// The data must be valid UTF-8
321321
///
322-
/// `p` must be non-null, even for zero-length str.
322+
/// `p` must be non-null, even for zero-length strs, because non-zero bits
323+
/// are required to distinguish between a zero-length str within `Some()`
324+
/// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
325+
/// for zero-length strs, though.
323326
///
324327
/// # Caveat
325328
///

0 commit comments

Comments
 (0)