Rollup merge of #123374 - mgeier:doc-slice-from-raw-parts, r=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 #120608.
This commit is contained in:
commit
8d3b9a19cf
@ -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
|
/// [valid]: ptr#safety
|
||||||
/// [`NonNull::dangling()`]: ptr::NonNull::dangling
|
/// [`NonNull::dangling()`]: ptr::NonNull::dangling
|
||||||
#[inline]
|
#[inline]
|
||||||
|
Loading…
x
Reference in New Issue
Block a user