From 08f761fb838a43589a30c8d5f9c26c11f7102bc8 Mon Sep 17 00:00:00 2001 From: Matthias Geier Date: Tue, 2 Apr 2024 18:54:24 +0200 Subject: [PATCH] DOC: Add FFI example for slice::from_raw_parts() --- core/src/slice/raw.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/core/src/slice/raw.rs b/core/src/slice/raw.rs index 29a12f106c5ed..d001688d79d80 100644 --- a/core/src/slice/raw.rs +++ b/core/src/slice/raw.rs @@ -83,6 +83,27 @@ 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; +/// +/// unsafe extern "C" fn handle_slice(ptr: *const f32, len: usize) { +/// let data = if ptr.is_null() { +/// // `len` is assumed to be 0. +/// &[] +/// } else { +/// unsafe { slice::from_raw_parts(ptr, len) } +/// }; +/// dbg!(data); +/// // ... +/// } +/// ``` +/// /// [valid]: ptr#safety /// [`NonNull::dangling()`]: ptr::NonNull::dangling #[inline]