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