Skip to content

Commit

Permalink
Extend the example code and assert the result
Browse files Browse the repository at this point in the history
  • Loading branch information
mgeier committed Apr 26, 2024
1 parent 678e5a0 commit 2a5af32
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions core/src/slice/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,21 +92,28 @@ use crate::ub_checks;
/// ```
/// 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 handle_slice(ptr: *const f32, len: usize) {
/// 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) }
/// };
/// dbg!(data);
/// // ...
/// data.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
Expand Down

0 comments on commit 2a5af32

Please sign in to comment.