Skip to content

Commit

Permalink
Rollup merge of rust-lang#123374 - mgeier:doc-slice-from-raw-parts, r…
Browse files Browse the repository at this point in the history
…=scottmcm

DOC: Add FFI example for slice::from_raw_parts()

For some discussion, see https://users.rust-lang.org/t/missing-guidance-on-converting-ffi-ptr-length-to-slice/106048

See also rust-lang#120608.
  • Loading branch information
workingjubilee authored Jun 12, 2024
2 parents 76c7382 + 30b676c commit 50068e1
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions library/core/src/slice/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,39 @@ use crate::ub_checks;
/// }
/// ```
///
/// ### FFI: Handling null pointers
///
/// In languages such as C++, pointers to empty collections are not guaranteed to be non-null.
/// When accepting such pointers, they have to be checked for null-ness to avoid undefined
/// behavior.
///
/// ```
/// use std::slice;
///
/// /// Sum the elements of an FFI slice.
/// ///
/// /// # Safety
/// ///
/// /// If ptr is not NULL, it must be correctly aligned and
/// /// point to `len` initialized items of type `f32`.
/// unsafe extern "C" fn sum_slice(ptr: *const f32, len: usize) -> f32 {
/// let data = if ptr.is_null() {
/// // `len` is assumed to be 0.
/// &[]
/// } else {
/// // SAFETY: see function docstring.
/// unsafe { slice::from_raw_parts(ptr, len) }
/// };
/// data.into_iter().sum()
/// }
///
/// // This could be the result of C++'s std::vector::data():
/// let ptr = std::ptr::null();
/// // And this could be std::vector::size():
/// let len = 0;
/// assert_eq!(unsafe { sum_slice(ptr, len) }, 0.0);
/// ```
///
/// [valid]: ptr#safety
/// [`NonNull::dangling()`]: ptr::NonNull::dangling
#[inline]
Expand Down

0 comments on commit 50068e1

Please sign in to comment.