]> git.lizzy.rs Git - rust.git/blob - library/core/src/slice/raw.rs
Merge commit 'dc5423ad448877e33cca28db2f1445c9c4473c75' into clippyup
[rust.git] / library / core / src / slice / raw.rs
1 //! Free functions to create `&[T]` and `&mut [T]`.
2
3 use crate::array;
4 use crate::ops::Range;
5 use crate::ptr;
6
7 /// Forms a slice from a pointer and a length.
8 ///
9 /// The `len` argument is the number of **elements**, not the number of bytes.
10 ///
11 /// # Safety
12 ///
13 /// Behavior is undefined if any of the following conditions are violated:
14 ///
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:
17 ///
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()`].
26 ///
27 /// * `data` must point to `len` consecutive properly initialized values of type `T`.
28 ///
29 /// * The memory referenced by the returned slice must not be mutated for the duration
30 ///   of lifetime `'a`, except inside an `UnsafeCell`.
31 ///
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`].
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 /// [valid]: ptr#safety
84 /// [`NonNull::dangling()`]: ptr::NonNull::dangling
85 #[inline]
86 #[stable(feature = "rust1", since = "1.0.0")]
87 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
88 pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
89     debug_check_data_len(data, len);
90
91     // SAFETY: the caller must uphold the safety contract for `from_raw_parts`.
92     unsafe { &*ptr::slice_from_raw_parts(data, len) }
93 }
94
95 /// Performs the same functionality as [`from_raw_parts`], except that a
96 /// mutable slice is returned.
97 ///
98 /// # Safety
99 ///
100 /// Behavior is undefined if any of the following conditions are violated:
101 ///
102 /// * `data` must be [valid] for both reads and writes for `len * mem::size_of::<T>()` many bytes,
103 ///   and it must be properly aligned. This means in particular:
104 ///
105 ///     * The entire memory range of this slice must be contained within a single allocated object!
106 ///       Slices can never span across multiple allocated objects.
107 ///     * `data` must be non-null and aligned even for zero-length slices. One
108 ///       reason for this is that enum layout optimizations may rely on references
109 ///       (including slices of any length) being aligned and non-null to distinguish
110 ///       them from other data. You can obtain a pointer that is usable as `data`
111 ///       for zero-length slices using [`NonNull::dangling()`].
112 ///
113 /// * `data` must point to `len` consecutive properly initialized values of type `T`.
114 ///
115 /// * The memory referenced by the returned slice must not be accessed through any other pointer
116 ///   (not derived from the return value) for the duration of lifetime `'a`.
117 ///   Both read and write accesses are forbidden.
118 ///
119 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
120 ///   See the safety documentation of [`pointer::offset`].
121 ///
122 /// [valid]: ptr#safety
123 /// [`NonNull::dangling()`]: ptr::NonNull::dangling
124 #[inline]
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
127 pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
128     debug_check_data_len(data as _, len);
129
130     // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`.
131     unsafe { &mut *ptr::slice_from_raw_parts_mut(data, len) }
132 }
133
134 // 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
135 #[cfg(debug_assertions)]
136 #[unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
137 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
138 const fn debug_check_data_len<T>(data: *const T, len: usize) {
139     fn rt_check<T>(data: *const T) {
140         use crate::intrinsics::is_aligned_and_not_null;
141
142         assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
143     }
144
145     const fn noop<T>(_: *const T) {}
146
147     // SAFETY:
148     //
149     // `rt_check` is just a debug assert to hint users that they are causing UB,
150     // it is not required for safety (the safety must be guatanteed by
151     // the `from_raw_parts[_mut]` caller).
152     //
153     // As per our safety precondition, we may assume that assertion above never fails.
154     // Therefore, noop and rt_check are observably equivalent.
155     unsafe {
156         crate::intrinsics::const_eval_select((data,), noop, rt_check);
157     }
158
159     assert!(
160         crate::mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
161         "attempt to create slice covering at least half the address space"
162     );
163 }
164
165 #[cfg(not(debug_assertions))]
166 const fn debug_check_data_len<T>(_data: *const T, _len: usize) {}
167
168 /// Converts a reference to T into a slice of length 1 (without copying).
169 #[stable(feature = "from_ref", since = "1.28.0")]
170 #[rustc_const_unstable(feature = "const_slice_from_ref", issue = "90206")]
171 pub const fn from_ref<T>(s: &T) -> &[T] {
172     array::from_ref(s)
173 }
174
175 /// Converts a reference to T into a slice of length 1 (without copying).
176 #[stable(feature = "from_ref", since = "1.28.0")]
177 #[rustc_const_unstable(feature = "const_slice_from_ref", issue = "90206")]
178 pub const fn from_mut<T>(s: &mut T) -> &mut [T] {
179     array::from_mut(s)
180 }
181
182 /// Forms a slice from a pointer range.
183 ///
184 /// This function is useful for interacting with foreign interfaces which
185 /// use two pointers to refer to a range of elements in memory, as is
186 /// common in C++.
187 ///
188 /// # Safety
189 ///
190 /// Behavior is undefined if any of the following conditions are violated:
191 ///
192 /// * The `start` pointer of the range must be a [valid] and properly aligned pointer
193 ///   to the first element of a slice.
194 ///
195 /// * The `end` pointer must be a [valid] and properly aligned pointer to *one past*
196 ///   the last element, such that the offset from the end to the start pointer is
197 ///   the length of the slice.
198 ///
199 /// * The range must contain `N` consecutive properly initialized values of type `T`:
200 ///
201 ///     * The entire memory range of this slice must be contained within a single allocated object!
202 ///       Slices can never span across multiple allocated objects.
203 ///
204 /// * The memory referenced by the returned slice must not be mutated for the duration
205 ///   of lifetime `'a`, except inside an `UnsafeCell`.
206 ///
207 /// * The total length of the range must be no larger than `isize::MAX`.
208 ///   See the safety documentation of [`pointer::offset`].
209 ///
210 /// Note that a range created from [`slice::as_ptr_range`] fulfills these requirements.
211 ///
212 /// # Caveat
213 ///
214 /// The lifetime for the returned slice is inferred from its usage. To
215 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
216 /// source lifetime is safe in the context, such as by providing a helper
217 /// function taking the lifetime of a host value for the slice, or by explicit
218 /// annotation.
219 ///
220 /// # Examples
221 ///
222 /// ```
223 /// #![feature(slice_from_ptr_range)]
224 ///
225 /// use core::slice;
226 ///
227 /// let x = [1, 2, 3];
228 /// let range = x.as_ptr_range();
229 ///
230 /// unsafe {
231 ///     assert_eq!(slice::from_ptr_range(range), &x);
232 /// }
233 /// ```
234 ///
235 /// [valid]: ptr#safety
236 #[unstable(feature = "slice_from_ptr_range", issue = "89792")]
237 pub unsafe fn from_ptr_range<'a, T>(range: Range<*const T>) -> &'a [T] {
238     // SAFETY: the caller must uphold the safety contract for `from_ptr_range`.
239     unsafe { from_raw_parts(range.start, range.end.offset_from(range.start) as usize) }
240 }
241
242 /// Performs the same functionality as [`from_ptr_range`], except that a
243 /// mutable slice is returned.
244 ///
245 /// # Safety
246 ///
247 /// Behavior is undefined if any of the following conditions are violated:
248 ///
249 /// * The `start` pointer of the range must be a [valid] and properly aligned pointer
250 ///   to the first element of a slice.
251 ///
252 /// * The `end` pointer must be a [valid] and properly aligned pointer to *one past*
253 ///   the last element, such that the offset from the end to the start pointer is
254 ///   the length of the slice.
255 ///
256 /// * The range must contain `N` consecutive properly initialized values of type `T`:
257 ///
258 ///     * The entire memory range of this slice must be contained within a single allocated object!
259 ///       Slices can never span across multiple allocated objects.
260 ///
261 /// * The memory referenced by the returned slice must not be accessed through any other pointer
262 ///   (not derived from the return value) for the duration of lifetime `'a`.
263 ///   Both read and write accesses are forbidden.
264 ///
265 /// * The total length of the range must be no larger than `isize::MAX`.
266 ///   See the safety documentation of [`pointer::offset`].
267 ///
268 /// Note that a range created from [`slice::as_mut_ptr_range`] fulfills these requirements.
269 ///
270 /// # Examples
271 ///
272 /// ```
273 /// #![feature(slice_from_ptr_range)]
274 ///
275 /// use core::slice;
276 ///
277 /// let mut x = [1, 2, 3];
278 /// let range = x.as_mut_ptr_range();
279 ///
280 /// unsafe {
281 ///     assert_eq!(slice::from_mut_ptr_range(range), &mut [1, 2, 3]);
282 /// }
283 /// ```
284 ///
285 /// [valid]: ptr#safety
286 #[unstable(feature = "slice_from_ptr_range", issue = "89792")]
287 pub unsafe fn from_mut_ptr_range<'a, T>(range: Range<*mut T>) -> &'a mut [T] {
288     // SAFETY: the caller must uphold the safety contract for `from_mut_ptr_range`.
289     unsafe { from_raw_parts_mut(range.start, range.end.offset_from(range.start) as usize) }
290 }