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 * mem::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 allocated object!
18/// Slices can never span across multiple allocated objects. 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 * mem::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 allocated objects_, 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 allocated objects...
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"]
123pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
124 // SAFETY: the caller must uphold the safety contract for `from_raw_parts`.
125 unsafe {
126 ub_checks::assert_unsafe_precondition!(
127 check_language_ub,
128 "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`",
129 (
130 data: *mut () = data as *mut (),
131 size: usize = size_of::<T>(),
132 align: usize = align_of::<T>(),
133 len: usize = len,
134 ) =>
135 ub_checks::maybe_is_aligned_and_not_null(data, align, false)
136 && ub_checks::is_valid_allocation_size(size, len)
137 );
138 &*ptr::slice_from_raw_parts(data, len)
139 }
140}
141
142/// Performs the same functionality as [`from_raw_parts`], except that a
143/// mutable slice is returned.
144///
145/// # Safety
146///
147/// Behavior is undefined if any of the following conditions are violated:
148///
149/// * `data` must be non-null, [valid] for both reads and writes for `len * mem::size_of::<T>()` many bytes,
150/// and it must be properly aligned. This means in particular:
151///
152/// * The entire memory range of this slice must be contained within a single allocated object!
153/// Slices can never span across multiple allocated objects.
154/// * `data` must be non-null and aligned even for zero-length slices or slices of ZSTs. One
155/// reason for this is that enum layout optimizations may rely on references
156/// (including slices of any length) being aligned and non-null to distinguish
157/// them from other data. You can obtain a pointer that is usable as `data`
158/// for zero-length slices using [`NonNull::dangling()`].
159///
160/// * `data` must point to `len` consecutive properly initialized values of type `T`.
161///
162/// * The memory referenced by the returned slice must not be accessed through any other pointer
163/// (not derived from the return value) for the duration of lifetime `'a`.
164/// Both read and write accesses are forbidden.
165///
166/// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`,
167/// and adding that size to `data` must not "wrap around" the address space.
168/// See the safety documentation of [`pointer::offset`].
169///
170/// [valid]: ptr#safety
171/// [`NonNull::dangling()`]: ptr::NonNull::dangling
172#[inline]
173#[stable(feature = "rust1", since = "1.0.0")]
174#[rustc_const_stable(feature = "const_slice_from_raw_parts_mut", since = "1.83.0")]
175#[must_use]
176#[rustc_diagnostic_item = "slice_from_raw_parts_mut"]
177pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
178 // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`.
179 unsafe {
180 ub_checks::assert_unsafe_precondition!(
181 check_language_ub,
182 "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`",
183 (
184 data: *mut () = data as *mut (),
185 size: usize = size_of::<T>(),
186 align: usize = align_of::<T>(),
187 len: usize = len,
188 ) =>
189 ub_checks::maybe_is_aligned_and_not_null(data, align, false)
190 && ub_checks::is_valid_allocation_size(size, len)
191 );
192 &mut *ptr::slice_from_raw_parts_mut(data, len)
193 }
194}
195
196/// Converts a reference to T into a slice of length 1 (without copying).
197#[stable(feature = "from_ref", since = "1.28.0")]
198#[rustc_const_stable(feature = "const_slice_from_ref_shared", since = "1.63.0")]
199#[must_use]
200pub const fn from_ref<T>(s: &T) -> &[T] {
201 array::from_ref(s)
202}
203
204/// Converts a reference to T into a slice of length 1 (without copying).
205#[stable(feature = "from_ref", since = "1.28.0")]
206#[rustc_const_stable(feature = "const_slice_from_ref", since = "1.83.0")]
207#[must_use]
208pub const fn from_mut<T>(s: &mut T) -> &mut [T] {
209 array::from_mut(s)
210}
211
212/// Forms a slice from a pointer range.
213///
214/// This function is useful for interacting with foreign interfaces which
215/// use two pointers to refer to a range of elements in memory, as is
216/// common in C++.
217///
218/// # Safety
219///
220/// Behavior is undefined if any of the following conditions are violated:
221///
222/// * The `start` pointer of the range must be a non-null, [valid] and properly aligned pointer
223/// to the first element of a slice.
224///
225/// * The `end` pointer must be a [valid] and properly aligned pointer to *one past*
226/// the last element, such that the offset from the end to the start pointer is
227/// the length of the slice.
228///
229/// * The entire memory range of this slice must be contained within a single allocated object!
230/// Slices can never span across multiple allocated objects.
231///
232/// * The range must contain `N` consecutive properly initialized values of type `T`.
233///
234/// * The memory referenced by the returned slice must not be mutated for the duration
235/// of lifetime `'a`, except inside an `UnsafeCell`.
236///
237/// * The total length of the range must be no larger than `isize::MAX`,
238/// and adding that size to `start` must not "wrap around" the address space.
239/// See the safety documentation of [`pointer::offset`].
240///
241/// Note that a range created from [`slice::as_ptr_range`] fulfills these requirements.
242///
243/// # Panics
244///
245/// This function panics if `T` is a Zero-Sized Type (“ZST”).
246///
247/// # Caveat
248///
249/// The lifetime for the returned slice is inferred from its usage. To
250/// prevent accidental misuse, it's suggested to tie the lifetime to whichever
251/// source lifetime is safe in the context, such as by providing a helper
252/// function taking the lifetime of a host value for the slice, or by explicit
253/// annotation.
254///
255/// # Examples
256///
257/// ```
258/// #![feature(slice_from_ptr_range)]
259///
260/// use core::slice;
261///
262/// let x = [1, 2, 3];
263/// let range = x.as_ptr_range();
264///
265/// unsafe {
266/// assert_eq!(slice::from_ptr_range(range), &x);
267/// }
268/// ```
269///
270/// [valid]: ptr#safety
271#[unstable(feature = "slice_from_ptr_range", issue = "89792")]
272#[rustc_const_unstable(feature = "const_slice_from_ptr_range", issue = "89792")]
273pub const unsafe fn from_ptr_range<'a, T>(range: Range<*const T>) -> &'a [T] {
274 // SAFETY: the caller must uphold the safety contract for `from_ptr_range`.
275 unsafe { from_raw_parts(range.start, range.end.sub_ptr(range.start)) }
276}
277
278/// Forms a mutable slice from a pointer range.
279///
280/// This is the same functionality as [`from_ptr_range`], except that a
281/// mutable slice is returned.
282///
283/// This function is useful for interacting with foreign interfaces which
284/// use two pointers to refer to a range of elements in memory, as is
285/// common in C++.
286///
287/// # Safety
288///
289/// Behavior is undefined if any of the following conditions are violated:
290///
291/// * The `start` pointer of the range must be a non-null, [valid] and properly aligned pointer
292/// to the first element of a slice.
293///
294/// * The `end` pointer must be a [valid] and properly aligned pointer to *one past*
295/// the last element, such that the offset from the end to the start pointer is
296/// the length of the slice.
297///
298/// * The entire memory range of this slice must be contained within a single allocated object!
299/// Slices can never span across multiple allocated objects.
300///
301/// * The range must contain `N` consecutive properly initialized values of type `T`.
302///
303/// * The memory referenced by the returned slice must not be accessed through any other pointer
304/// (not derived from the return value) for the duration of lifetime `'a`.
305/// Both read and write accesses are forbidden.
306///
307/// * The total length of the range must be no larger than `isize::MAX`,
308/// and adding that size to `start` must not "wrap around" the address space.
309/// See the safety documentation of [`pointer::offset`].
310///
311/// Note that a range created from [`slice::as_mut_ptr_range`] fulfills these requirements.
312///
313/// # Panics
314///
315/// This function panics if `T` is a Zero-Sized Type (“ZST”).
316///
317/// # Caveat
318///
319/// The lifetime for the returned slice is inferred from its usage. To
320/// prevent accidental misuse, it's suggested to tie the lifetime to whichever
321/// source lifetime is safe in the context, such as by providing a helper
322/// function taking the lifetime of a host value for the slice, or by explicit
323/// annotation.
324///
325/// # Examples
326///
327/// ```
328/// #![feature(slice_from_ptr_range)]
329///
330/// use core::slice;
331///
332/// let mut x = [1, 2, 3];
333/// let range = x.as_mut_ptr_range();
334///
335/// unsafe {
336/// assert_eq!(slice::from_mut_ptr_range(range), &mut [1, 2, 3]);
337/// }
338/// ```
339///
340/// [valid]: ptr#safety
341#[unstable(feature = "slice_from_ptr_range", issue = "89792")]
342#[rustc_const_unstable(feature = "const_slice_from_mut_ptr_range", issue = "89792")]
343pub const unsafe fn from_mut_ptr_range<'a, T>(range: Range<*mut T>) -> &'a mut [T] {
344 // SAFETY: the caller must uphold the safety contract for `from_mut_ptr_range`.
345 unsafe { from_raw_parts_mut(range.start, range.end.sub_ptr(range.start)) }
346}