Rollup merge of #123374 - mgeier:doc-slice-from-raw-parts, r=scottmcm · model-checking/verify-rust-std@d469394 (original) (raw)
`@@ -82,6 +82,39 @@ use crate::ub_checks;
`
82
82
`/// }
`
83
83
```` /// ```
`84`
`84`
`///
`
``
`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
`+
///
`
85
118
`/// [valid]: ptr#safety
`
86
119
`` /// [NonNull::dangling()
]: ptr::NonNull::dangling
``
87
120
`#[inline]
`