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
This commit is contained in:
bors 2017-04-30 07:58:10 +00:00
commit c0f86f5927
2 changed files with 10 additions and 3 deletions

View File

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

View File

@ -319,7 +319,10 @@ pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
///
/// The data must be valid UTF-8
///
/// `p` must be non-null, even for zero-length str.
/// `p` must be non-null, even for zero-length strs, because non-zero bits
/// are required to distinguish between a zero-length str within `Some()`
/// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
/// for zero-length strs, though.
///
/// # Caveat
///