Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit b1aca86

Browse files
authoredMar 8, 2024
Rollup merge of #120608 - kornelski:slice-ptr-doc, r=cuviper
Docs for std::ptr::slice_from_raw_parts
2 parents d774fbe + f4b65f5 commit b1aca86

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed
 

‎library/core/src/ptr/mod.rs

+26-2
Original file line numberDiff line numberDiff line change
@@ -796,6 +796,17 @@ pub const fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
796796
/// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
797797
/// assert_eq!(unsafe { &*slice }[2], 7);
798798
/// ```
799+
///
800+
/// You must ensure that the pointer is valid and not null before dereferencing
801+
/// the raw slice. A slice reference must never have a null pointer, even if it's empty.
802+
///
803+
/// ```rust,should_panic
804+
/// use std::ptr;
805+
/// let danger: *const [u8] = ptr::slice_from_raw_parts(ptr::null(), 0);
806+
/// unsafe {
807+
/// danger.as_ref().expect("references must not be null");
808+
/// }
809+
/// ```
799810
#[inline]
800811
#[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
801812
#[rustc_const_stable(feature = "const_slice_from_raw_parts", since = "1.64.0")]
@@ -805,11 +816,13 @@ pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
805816
from_raw_parts(data.cast(), len)
806817
}
807818

819+
/// Forms a raw mutable slice from a pointer and a length.
820+
///
821+
/// The `len` argument is the number of **elements**, not the number of bytes.
822+
///
808823
/// Performs the same functionality as [`slice_from_raw_parts`], except that a
809824
/// raw mutable slice is returned, as opposed to a raw immutable slice.
810825
///
811-
/// See the documentation of [`slice_from_raw_parts`] for more details.
812-
///
813826
/// This function is safe, but actually using the return value is unsafe.
814827
/// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
815828
///
@@ -830,6 +843,17 @@ pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
830843
///
831844
/// assert_eq!(unsafe { &*slice }[2], 99);
832845
/// ```
846+
///
847+
/// You must ensure that the pointer is valid and not null before dereferencing
848+
/// the raw slice. A slice reference must never have a null pointer, even if it's empty.
849+
///
850+
/// ```rust,should_panic
851+
/// use std::ptr;
852+
/// let danger: *mut [u8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 0);
853+
/// unsafe {
854+
/// danger.as_mut().expect("references must not be null");
855+
/// }
856+
/// ```
833857
#[inline]
834858
#[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
835859
#[rustc_const_unstable(feature = "const_slice_from_raw_parts_mut", issue = "67456")]

0 commit comments

Comments
 (0)
Failed to load comments.