1 //! Free functions to create `&[T]` and `&mut [T]`.
7 /// Forms a slice from a pointer and a length.
9 /// The `len` argument is the number of **elements**, not the number of bytes.
13 /// Behavior is undefined if any of the following conditions are violated:
15 /// * `data` must be [valid] for reads for `len * mem::size_of::<T>()` many bytes,
16 /// and it must be properly aligned. This means in particular:
18 /// * The entire memory range of this slice must be contained within a single allocated object!
19 /// Slices can never span across multiple allocated objects. See [below](#incorrect-usage)
20 /// for an example incorrectly not taking this into account.
21 /// * `data` must be non-null and aligned even for zero-length slices. One
22 /// reason for this is that enum layout optimizations may rely on references
23 /// (including slices of any length) being aligned and non-null to distinguish
24 /// them from other data. You can obtain a pointer that is usable as `data`
25 /// for zero-length slices using [`NonNull::dangling()`].
27 /// * `data` must point to `len` consecutive properly initialized values of type `T`.
29 /// * The memory referenced by the returned slice must not be mutated for the duration
30 /// of lifetime `'a`, except inside an `UnsafeCell`.
32 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
33 /// See the safety documentation of [`pointer::offset`].
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
48 /// // manifest a slice for a single element
50 /// let ptr = &x as *const _;
51 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
52 /// assert_eq!(slice[0], 42);
55 /// ### Incorrect usage
57 /// The following `join_slices` function is **unsound** ⚠️
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!");
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())
75 /// // `a` and `b` are different allocated objects...
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
83 /// [valid]: ptr#safety
84 /// [`NonNull::dangling()`]: ptr::NonNull::dangling
86 #[stable(feature = "rust1", since = "1.0.0")]
87 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
89 pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
90 debug_check_data_len(data, len);
92 // SAFETY: the caller must uphold the safety contract for `from_raw_parts`.
93 unsafe { &*ptr::slice_from_raw_parts(data, len) }
96 /// Performs the same functionality as [`from_raw_parts`], except that a
97 /// mutable slice is returned.
101 /// Behavior is undefined if any of the following conditions are violated:
103 /// * `data` must be [valid] for both reads and writes for `len * mem::size_of::<T>()` many bytes,
104 /// and it must be properly aligned. This means in particular:
106 /// * The entire memory range of this slice must be contained within a single allocated object!
107 /// Slices can never span across multiple allocated objects.
108 /// * `data` must be non-null and aligned even for zero-length slices. One
109 /// reason for this is that enum layout optimizations may rely on references
110 /// (including slices of any length) being aligned and non-null to distinguish
111 /// them from other data. You can obtain a pointer that is usable as `data`
112 /// for zero-length slices using [`NonNull::dangling()`].
114 /// * `data` must point to `len` consecutive properly initialized values of type `T`.
116 /// * The memory referenced by the returned slice must not be accessed through any other pointer
117 /// (not derived from the return value) for the duration of lifetime `'a`.
118 /// Both read and write accesses are forbidden.
120 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
121 /// See the safety documentation of [`pointer::offset`].
123 /// [valid]: ptr#safety
124 /// [`NonNull::dangling()`]: ptr::NonNull::dangling
126 #[stable(feature = "rust1", since = "1.0.0")]
127 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
129 pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
130 debug_check_data_len(data as _, len);
132 // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`.
133 unsafe { &mut *ptr::slice_from_raw_parts_mut(data, len) }
136 // In debug builds checks that `data` pointer is aligned and non-null and that slice with given `len` would cover less than half the address space
137 #[cfg(debug_assertions)]
138 #[unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
139 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
140 const fn debug_check_data_len<T>(data: *const T, len: usize) {
141 fn rt_check<T>(data: *const T) {
142 use crate::intrinsics::is_aligned_and_not_null;
144 assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
147 const fn noop<T>(_: *const T) {}
151 // `rt_check` is just a debug assert to hint users that they are causing UB,
152 // it is not required for safety (the safety must be guatanteed by
153 // the `from_raw_parts[_mut]` caller).
155 // As per our safety precondition, we may assume that assertion above never fails.
156 // Therefore, noop and rt_check are observably equivalent.
158 crate::intrinsics::const_eval_select((data,), noop, rt_check);
162 crate::mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
163 "attempt to create slice covering at least half the address space"
167 #[cfg(not(debug_assertions))]
168 const fn debug_check_data_len<T>(_data: *const T, _len: usize) {}
170 /// Converts a reference to T into a slice of length 1 (without copying).
171 #[stable(feature = "from_ref", since = "1.28.0")]
172 #[rustc_const_unstable(feature = "const_slice_from_ref", issue = "90206")]
174 pub const fn from_ref<T>(s: &T) -> &[T] {
178 /// Converts a reference to T into a slice of length 1 (without copying).
179 #[stable(feature = "from_ref", since = "1.28.0")]
180 #[rustc_const_unstable(feature = "const_slice_from_ref", issue = "90206")]
182 pub const fn from_mut<T>(s: &mut T) -> &mut [T] {
186 /// Forms a slice from a pointer range.
188 /// This function is useful for interacting with foreign interfaces which
189 /// use two pointers to refer to a range of elements in memory, as is
194 /// Behavior is undefined if any of the following conditions are violated:
196 /// * The `start` pointer of the range must be a [valid] and properly aligned pointer
197 /// to the first element of a slice.
199 /// * The `end` pointer must be a [valid] and properly aligned pointer to *one past*
200 /// the last element, such that the offset from the end to the start pointer is
201 /// the length of the slice.
203 /// * The range must contain `N` consecutive properly initialized values of type `T`:
205 /// * The entire memory range of this slice must be contained within a single allocated object!
206 /// Slices can never span across multiple allocated objects.
208 /// * The memory referenced by the returned slice must not be mutated for the duration
209 /// of lifetime `'a`, except inside an `UnsafeCell`.
211 /// * The total length of the range must be no larger than `isize::MAX`.
212 /// See the safety documentation of [`pointer::offset`].
214 /// Note that a range created from [`slice::as_ptr_range`] fulfills these requirements.
218 /// The lifetime for the returned slice is inferred from its usage. To
219 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
220 /// source lifetime is safe in the context, such as by providing a helper
221 /// function taking the lifetime of a host value for the slice, or by explicit
227 /// #![feature(slice_from_ptr_range)]
231 /// let x = [1, 2, 3];
232 /// let range = x.as_ptr_range();
235 /// assert_eq!(slice::from_ptr_range(range), &x);
239 /// [valid]: ptr#safety
240 #[unstable(feature = "slice_from_ptr_range", issue = "89792")]
241 pub unsafe fn from_ptr_range<'a, T>(range: Range<*const T>) -> &'a [T] {
242 // SAFETY: the caller must uphold the safety contract for `from_ptr_range`.
243 unsafe { from_raw_parts(range.start, range.end.offset_from(range.start) as usize) }
246 /// Performs the same functionality as [`from_ptr_range`], except that a
247 /// mutable slice is returned.
251 /// Behavior is undefined if any of the following conditions are violated:
253 /// * The `start` pointer of the range must be a [valid] and properly aligned pointer
254 /// to the first element of a slice.
256 /// * The `end` pointer must be a [valid] and properly aligned pointer to *one past*
257 /// the last element, such that the offset from the end to the start pointer is
258 /// the length of the slice.
260 /// * The range must contain `N` consecutive properly initialized values of type `T`:
262 /// * The entire memory range of this slice must be contained within a single allocated object!
263 /// Slices can never span across multiple allocated objects.
265 /// * The memory referenced by the returned slice must not be accessed through any other pointer
266 /// (not derived from the return value) for the duration of lifetime `'a`.
267 /// Both read and write accesses are forbidden.
269 /// * The total length of the range must be no larger than `isize::MAX`.
270 /// See the safety documentation of [`pointer::offset`].
272 /// Note that a range created from [`slice::as_mut_ptr_range`] fulfills these requirements.
277 /// #![feature(slice_from_ptr_range)]
281 /// let mut x = [1, 2, 3];
282 /// let range = x.as_mut_ptr_range();
285 /// assert_eq!(slice::from_mut_ptr_range(range), &mut [1, 2, 3]);
289 /// [valid]: ptr#safety
290 #[unstable(feature = "slice_from_ptr_range", issue = "89792")]
291 pub unsafe fn from_mut_ptr_range<'a, T>(range: Range<*mut T>) -> &'a mut [T] {
292 // SAFETY: the caller must uphold the safety contract for `from_mut_ptr_range`.
293 unsafe { from_raw_parts_mut(range.start, range.end.offset_from(range.start) as usize) }