1 //! Free functions to create `&[T]` and `&mut [T]`.
6 /// Forms a slice from a pointer and a length.
8 /// The `len` argument is the number of **elements**, not the number of bytes.
12 /// Behavior is undefined if any of the following conditions are violated:
14 /// * `data` must be [valid] for reads for `len * mem::size_of::<T>()` many bytes,
15 /// and it must be properly aligned. This means in particular:
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. 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()`].
26 /// * `data` must point to `len` consecutive properly initialized values of type `T`.
28 /// * The memory referenced by the returned slice must not be mutated for the duration
29 /// of lifetime `'a`, except inside an `UnsafeCell`.
31 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
32 /// See the safety documentation of [`pointer::offset`].
36 /// The lifetime for the returned slice is inferred from its usage. To
37 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
38 /// source lifetime is safe in the context, such as by providing a helper
39 /// function taking the lifetime of a host value for the slice, or by explicit
47 /// // manifest a slice for a single element
49 /// let ptr = &x as *const _;
50 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
51 /// assert_eq!(slice[0], 42);
54 /// ### Incorrect usage
56 /// The following `join_slices` function is **unsound** ⚠️
61 /// fn join_slices<'a, T>(fst: &'a [T], snd: &'a [T]) -> &'a [T] {
62 /// let fst_end = fst.as_ptr().wrapping_add(fst.len());
63 /// let snd_start = snd.as_ptr();
64 /// assert_eq!(fst_end, snd_start, "Slices must be contiguous!");
66 /// // The assertion above ensures `fst` and `snd` are contiguous, but they might
67 /// // still be contained within _different allocated objects_, in which case
68 /// // creating this slice is undefined behavior.
69 /// slice::from_raw_parts(fst.as_ptr(), fst.len() + snd.len())
74 /// // `a` and `b` are different allocated objects...
77 /// // ... which may nevertheless be laid out contiguously in memory: | a | b |
78 /// let _ = join_slices(slice::from_ref(&a), slice::from_ref(&b)); // UB
82 /// [valid]: ptr#safety
83 /// [`NonNull::dangling()`]: ptr::NonNull::dangling
85 #[stable(feature = "rust1", since = "1.0.0")]
86 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
87 pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
88 debug_check_data_len(data, len);
90 // SAFETY: the caller must uphold the safety contract for `from_raw_parts`.
91 unsafe { &*ptr::slice_from_raw_parts(data, len) }
94 /// Performs the same functionality as [`from_raw_parts`], except that a
95 /// mutable slice is returned.
99 /// Behavior is undefined if any of the following conditions are violated:
101 /// * `data` must be [valid] for both reads and writes for `len * mem::size_of::<T>()` many bytes,
102 /// and it must be properly aligned. This means in particular:
104 /// * The entire memory range of this slice must be contained within a single allocated object!
105 /// Slices can never span across multiple allocated objects.
106 /// * `data` must be non-null and aligned even for zero-length slices. One
107 /// reason for this is that enum layout optimizations may rely on references
108 /// (including slices of any length) being aligned and non-null to distinguish
109 /// them from other data. You can obtain a pointer that is usable as `data`
110 /// for zero-length slices using [`NonNull::dangling()`].
112 /// * `data` must point to `len` consecutive properly initialized values of type `T`.
114 /// * The memory referenced by the returned slice must not be accessed through any other pointer
115 /// (not derived from the return value) for the duration of lifetime `'a`.
116 /// Both read and write accesses are forbidden.
118 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
119 /// See the safety documentation of [`pointer::offset`].
121 /// [valid]: ptr#safety
122 /// [`NonNull::dangling()`]: ptr::NonNull::dangling
124 #[stable(feature = "rust1", since = "1.0.0")]
125 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
126 pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
127 debug_check_data_len(data as _, len);
129 // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`.
130 unsafe { &mut *ptr::slice_from_raw_parts_mut(data, len) }
133 // 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
134 #[cfg(all(not(bootstrap), debug_assertions))]
135 #[unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
136 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
137 const fn debug_check_data_len<T>(data: *const T, len: usize) {
138 fn rt_check<T>(data: *const T) {
139 use crate::intrinsics::is_aligned_and_not_null;
141 assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
144 const fn noop<T>(_: *const T) {}
148 // `rt_check` is just a debug assert to hint users that they are causing UB,
149 // it is not required for safety (the safety must be guatanteed by
150 // the `from_raw_parts[_mut]` caller).
152 // Since the checks are not required, we ignore them in CTFE as they can't
153 // be done there (alignment does not make much sense there).
155 crate::intrinsics::const_eval_select((data,), noop, rt_check);
159 crate::mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
160 "attempt to create slice covering at least half the address space"
164 #[cfg(not(all(not(bootstrap), debug_assertions)))]
165 const fn debug_check_data_len<T>(_data: *const T, _len: usize) {}
167 /// Converts a reference to T into a slice of length 1 (without copying).
168 #[stable(feature = "from_ref", since = "1.28.0")]
169 #[rustc_const_unstable(feature = "const_slice_from_ref", issue = "90206")]
170 pub const fn from_ref<T>(s: &T) -> &[T] {
174 /// Converts a reference to T into a slice of length 1 (without copying).
175 #[stable(feature = "from_ref", since = "1.28.0")]
176 #[rustc_const_unstable(feature = "const_slice_from_ref", issue = "90206")]
177 pub const fn from_mut<T>(s: &mut T) -> &mut [T] {