Skip to content

Commit d469394

Browse files
Rollup merge of rust-lang#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 rust-lang#120608.
2 parents f72e4a9 + f5305c1 commit d469394

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

core/src/slice/raw.rs

+33
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,39 @@ use crate::ub_checks;
8282
/// }
8383
/// ```
8484
///
85+
/// ### FFI: Handling null pointers
86+
///
87+
/// In languages such as C++, pointers to empty collections are not guaranteed to be non-null.
88+
/// When accepting such pointers, they have to be checked for null-ness to avoid undefined
89+
/// behavior.
90+
///
91+
/// ```
92+
/// use std::slice;
93+
///
94+
/// /// Sum the elements of an FFI slice.
95+
/// ///
96+
/// /// # Safety
97+
/// ///
98+
/// /// If ptr is not NULL, it must be correctly aligned and
99+
/// /// point to `len` initialized items of type `f32`.
100+
/// unsafe extern "C" fn sum_slice(ptr: *const f32, len: usize) -> f32 {
101+
/// let data = if ptr.is_null() {
102+
/// // `len` is assumed to be 0.
103+
/// &[]
104+
/// } else {
105+
/// // SAFETY: see function docstring.
106+
/// unsafe { slice::from_raw_parts(ptr, len) }
107+
/// };
108+
/// data.into_iter().sum()
109+
/// }
110+
///
111+
/// // This could be the result of C++'s std::vector::data():
112+
/// let ptr = std::ptr::null();
113+
/// // And this could be std::vector::size():
114+
/// let len = 0;
115+
/// assert_eq!(unsafe { sum_slice(ptr, len) }, 0.0);
116+
/// ```
117+
///
85118
/// [valid]: ptr#safety
86119
/// [`NonNull::dangling()`]: ptr::NonNull::dangling
87120
#[inline]

0 commit comments

Comments
 (0)