core/slice/raw.rs
1//! Free functions to create `&[T]` and `&mut [T]`.
2
3use crate::ops::Range;
4use crate::{array, ptr, ub_checks};
5
6/// Forms a slice from a pointer and a length.
7///
8/// The `len` argument is the number of **elements**, not the number of bytes.
9///
10/// # Safety
11///
12/// Behavior is undefined if any of the following conditions are violated:
13///
14/// * `data` must be non-null, [valid] for reads for `len * size_of::<T>()` many bytes,
15/// and it must be properly aligned. This means in particular:
16///
17/// * The entire memory range of this slice must be contained within a single allocation!
18/// Slices can never span across multiple allocations. See [below](#incorrect-usage)
19/// for an example incorrectly not taking this into account.
20/// * `data` must be non-null and aligned even for zero-length slices or slices of ZSTs. One
21/// reason for this is that enum layout optimizations may rely on references
22/// (including slices of any length) being aligned and non-null to distinguish
23/// them from other data. You can obtain a pointer that is usable as `data`
24/// for zero-length slices using [`NonNull::dangling()`].
25///
26/// * `data` must point to `len` consecutive properly initialized values of type `T`.
27///
28/// * The memory referenced by the returned slice must not be mutated for the duration
29/// of lifetime `'a`, except inside an `UnsafeCell`.
30///
31/// * The total size `len * size_of::<T>()` of the slice must be no larger than `isize::MAX`,
32/// and adding that size to `data` must not "wrap around" the address space.
33/// See the safety documentation of [`pointer::offset`].
34///
35/// # Caveat
36///
37/// The lifetime for the returned slice is inferred from its usage. To
38/// prevent accidental misuse, it's suggested to tie the lifetime to whichever
39/// source lifetime is safe in the context, such as by providing a helper
40/// function taking the lifetime of a host value for the slice, or by explicit
41/// annotation.
42///
43/// # Examples
44///
45/// ```
46/// use std::slice;
47///
48/// // manifest a slice for a single element
49/// let x = 42;
50/// let ptr = &x as *const _;
51/// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
52/// assert_eq!(slice[0], 42);
53/// ```
54///
55/// ### Incorrect usage
56///
57/// The following `join_slices` function is **unsound** ⚠️
58///
59/// ```rust,no_run
60/// use std::slice;
61///
62/// fn join_slices<'a, T>(fst: &'a [T], snd: &'a [T]) -> &'a [T] {
63/// let fst_end = fst.as_ptr().wrapping_add(fst.len());
64/// let snd_start = snd.as_ptr();
65/// assert_eq!(fst_end, snd_start, "Slices must be contiguous!");
66/// unsafe {
67/// // The assertion above ensures `fst` and `snd` are contiguous, but they might
68/// // still be contained within _different allocations_, in which case
69/// // creating this slice is undefined behavior.
70/// slice::from_raw_parts(fst.as_ptr(), fst.len() + snd.len())
71/// }
72/// }
73///
74/// fn main() {
75/// // `a` and `b` are different allocations...
76/// let a = 42;
77/// let b = 27;
78/// // ... which may nevertheless be laid out contiguously in memory: | a | b |
79/// let _ = join_slices(slice::from_ref(&a), slice::from_ref(&b)); // UB
80/// }
81/// ```
82///
83/// ### FFI: Handling null pointers
84///
85/// In languages such as C++, pointers to empty collections are not guaranteed to be non-null.
86/// When accepting such pointers, they have to be checked for null-ness to avoid undefined
87/// behavior.
88///
89/// ```
90/// use std::slice;
91///
92/// /// Sum the elements of an FFI slice.
93/// ///
94/// /// # Safety
95/// ///
96/// /// If ptr is not NULL, it must be correctly aligned and
97/// /// point to `len` initialized items of type `f32`.
98/// unsafe extern "C" fn sum_slice(ptr: *const f32, len: usize) -> f32 {
99/// let data = if ptr.is_null() {
100/// // `len` is assumed to be 0.
101/// &[]
102/// } else {
103/// // SAFETY: see function docstring.
104/// unsafe { slice::from_raw_parts(ptr, len) }
105/// };
106/// data.into_iter().sum()
107/// }
108///
109/// // This could be the result of C++'s std::vector::data():
110/// let ptr = std::ptr::null();
111/// // And this could be std::vector::size():
112/// let len = 0;
113/// assert_eq!(unsafe { sum_slice(ptr, len) }, 0.0);
114/// ```
115///
116/// [valid]: ptr#safety
117/// [`NonNull::dangling()`]: ptr::NonNull::dangling
118#[inline]
119#[stable(feature = "rust1", since = "1.0.0")]
120#[rustc_const_stable(feature = "const_slice_from_raw_parts", since = "1.64.0")]
121#[must_use]
122#[rustc_diagnostic_item = "slice_from_raw_parts"]
123#[track_caller]
124#[ferrocene::prevalidated]
125pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
126 // SAFETY: the caller must uphold the safety contract for `from_raw_parts`.
127 unsafe {
128 ub_checks::assert_unsafe_precondition!(
129 check_language_ub,
130 "slice::from_raw_parts requires the pointer to be aligned and non-null, and the total size of the slice not to exceed `isize::MAX`",
131 (
132 data: *mut () = data as *mut (),
133 size: usize = size_of::<T>(),
134 align: usize = align_of::<T>(),
135 len: usize = len,
136 ) =>
137 ub_checks::maybe_is_aligned_and_not_null(data, align, false)
138 && ub_checks::is_valid_allocation_size(size, len)
139 );
140 &*ptr::slice_from_raw_parts(data, len)
141 }
142}
143
144/// Performs the same functionality as [`from_raw_parts`], except that a
145/// mutable slice is returned.
146///
147/// # Safety
148///
149/// Behavior is undefined if any of the following conditions are violated:
150///
151/// * `data` must be non-null, [valid] for both reads and writes for `len * size_of::<T>()` many bytes,
152/// and it must be properly aligned. This means in particular:
153///
154/// * The entire memory range of this slice must be contained within a single allocation!
155/// Slices can never span across multiple allocations.
156/// * `data` must be non-null and aligned even for zero-length slices or slices of ZSTs. One
157/// reason for this is that enum layout optimizations may rely on references
158/// (including slices of any length) being aligned and non-null to distinguish
159/// them from other data. You can obtain a pointer that is usable as `data`
160/// for zero-length slices using [`NonNull::dangling()`].
161///
162/// * `data` must point to `len` consecutive properly initialized values of type `T`.
163///
164/// * The memory referenced by the returned slice must not be accessed through any other pointer
165/// (not derived from the return value) for the duration of lifetime `'a`.
166/// Both read and write accesses are forbidden.
167///
168/// * The total size `len * size_of::<T>()` of the slice must be no larger than `isize::MAX`,
169/// and adding that size to `data` must not "wrap around" the address space.
170/// See the safety documentation of [`pointer::offset`].
171///
172/// [valid]: ptr#safety
173/// [`NonNull::dangling()`]: ptr::NonNull::dangling
174#[inline]
175#[stable(feature = "rust1", since = "1.0.0")]
176#[rustc_const_stable(feature = "const_slice_from_raw_parts_mut", since = "1.83.0")]
177#[must_use]
178#[rustc_diagnostic_item = "slice_from_raw_parts_mut"]
179#[track_caller]
180#[ferrocene::prevalidated]
181pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
182 // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`.
183 unsafe {
184 ub_checks::assert_unsafe_precondition!(
185 check_language_ub,
186 "slice::from_raw_parts_mut requires the pointer to be aligned and non-null, and the total size of the slice not to exceed `isize::MAX`",
187 (
188 data: *mut () = data as *mut (),
189 size: usize = size_of::<T>(),
190 align: usize = align_of::<T>(),
191 len: usize = len,
192 ) =>
193 ub_checks::maybe_is_aligned_and_not_null(data, align, false)
194 && ub_checks::is_valid_allocation_size(size, len)
195 );
196 &mut *ptr::slice_from_raw_parts_mut(data, len)
197 }
198}
199
200/// Converts a reference to T into a slice of length 1 (without copying).
201#[stable(feature = "from_ref", since = "1.28.0")]
202#[rustc_const_stable(feature = "const_slice_from_ref_shared", since = "1.63.0")]
203#[rustc_diagnostic_item = "slice_from_ref"]
204#[must_use]
205#[ferrocene::prevalidated]
206pub const fn from_ref<T>(s: &T) -> &[T] {
207 array::from_ref(s)
208}
209
210/// Converts a reference to T into a slice of length 1 (without copying).
211#[stable(feature = "from_ref", since = "1.28.0")]
212#[rustc_const_stable(feature = "const_slice_from_ref", since = "1.83.0")]
213#[must_use]
214#[ferrocene::prevalidated]
215pub const fn from_mut<T>(s: &mut T) -> &mut [T] {
216 array::from_mut(s)
217}
218
219/// Forms a slice from a pointer range.
220///
221/// This function is useful for interacting with foreign interfaces which
222/// use two pointers to refer to a range of elements in memory, as is
223/// common in C++.
224///
225/// # Safety
226///
227/// Behavior is undefined if any of the following conditions are violated:
228///
229/// * The `start` pointer of the range must be a non-null, [valid] and properly aligned pointer
230/// to the first element of a slice.
231///
232/// * The `end` pointer must be a [valid] and properly aligned pointer to *one past*
233/// the last element, such that the offset from the end to the start pointer is
234/// the length of the slice.
235///
236/// * The entire memory range of this slice must be contained within a single allocation!
237/// Slices can never span across multiple allocations.
238///
239/// * The range must contain `N` consecutive properly initialized values of type `T`.
240///
241/// * The memory referenced by the returned slice must not be mutated for the duration
242/// of lifetime `'a`, except inside an `UnsafeCell`.
243///
244/// * The total length of the range must be no larger than `isize::MAX`,
245/// and adding that size to `start` must not "wrap around" the address space.
246/// See the safety documentation of [`pointer::offset`].
247///
248/// Note that a range created from [`slice::as_ptr_range`] fulfills these requirements.
249///
250/// # Panics
251///
252/// This function panics if `T` is a Zero-Sized Type (“ZST”).
253///
254/// # Caveat
255///
256/// The lifetime for the returned slice is inferred from its usage. To
257/// prevent accidental misuse, it's suggested to tie the lifetime to whichever
258/// source lifetime is safe in the context, such as by providing a helper
259/// function taking the lifetime of a host value for the slice, or by explicit
260/// annotation.
261///
262/// # Examples
263///
264/// ```
265/// #![feature(slice_from_ptr_range)]
266///
267/// use core::slice;
268///
269/// let x = [1, 2, 3];
270/// let range = x.as_ptr_range();
271///
272/// unsafe {
273/// assert_eq!(slice::from_ptr_range(range), &x);
274/// }
275/// ```
276///
277/// [valid]: ptr#safety
278#[unstable(feature = "slice_from_ptr_range", issue = "89792")]
279#[rustc_const_unstable(feature = "const_slice_from_ptr_range", issue = "89792")]
280#[track_caller]
281pub const unsafe fn from_ptr_range<'a, T>(range: Range<*const T>) -> &'a [T] {
282 // SAFETY: the caller must uphold the safety contract for `from_ptr_range`.
283 unsafe { from_raw_parts(range.start, range.end.offset_from_unsigned(range.start)) }
284}
285
286/// Forms a mutable slice from a pointer range.
287///
288/// This is the same functionality as [`from_ptr_range`], except that a
289/// mutable slice is returned.
290///
291/// This function is useful for interacting with foreign interfaces which
292/// use two pointers to refer to a range of elements in memory, as is
293/// common in C++.
294///
295/// # Safety
296///
297/// Behavior is undefined if any of the following conditions are violated:
298///
299/// * The `start` pointer of the range must be a non-null, [valid] and properly aligned pointer
300/// to the first element of a slice.
301///
302/// * The `end` pointer must be a [valid] and properly aligned pointer to *one past*
303/// the last element, such that the offset from the end to the start pointer is
304/// the length of the slice.
305///
306/// * The entire memory range of this slice must be contained within a single allocation!
307/// Slices can never span across multiple allocations.
308///
309/// * The range must contain `N` consecutive properly initialized values of type `T`.
310///
311/// * The memory referenced by the returned slice must not be accessed through any other pointer
312/// (not derived from the return value) for the duration of lifetime `'a`.
313/// Both read and write accesses are forbidden.
314///
315/// * The total length of the range must be no larger than `isize::MAX`,
316/// and adding that size to `start` must not "wrap around" the address space.
317/// See the safety documentation of [`pointer::offset`].
318///
319/// Note that a range created from [`slice::as_mut_ptr_range`] fulfills these requirements.
320///
321/// # Panics
322///
323/// This function panics if `T` is a Zero-Sized Type (“ZST”).
324///
325/// # Caveat
326///
327/// The lifetime for the returned slice is inferred from its usage. To
328/// prevent accidental misuse, it's suggested to tie the lifetime to whichever
329/// source lifetime is safe in the context, such as by providing a helper
330/// function taking the lifetime of a host value for the slice, or by explicit
331/// annotation.
332///
333/// # Examples
334///
335/// ```
336/// #![feature(slice_from_ptr_range)]
337///
338/// use core::slice;
339///
340/// let mut x = [1, 2, 3];
341/// let range = x.as_mut_ptr_range();
342///
343/// unsafe {
344/// assert_eq!(slice::from_mut_ptr_range(range), &mut [1, 2, 3]);
345/// }
346/// ```
347///
348/// [valid]: ptr#safety
349#[unstable(feature = "slice_from_ptr_range", issue = "89792")]
350#[rustc_const_unstable(feature = "const_slice_from_mut_ptr_range", issue = "89792")]
351pub const unsafe fn from_mut_ptr_range<'a, T>(range: Range<*mut T>) -> &'a mut [T] {
352 // SAFETY: the caller must uphold the safety contract for `from_mut_ptr_range`.
353 unsafe { from_raw_parts_mut(range.start, range.end.offset_from_unsigned(range.start)) }
354}