]> git.lizzy.rs Git - rust.git/blob - library/core/src/slice/raw.rs
Added docs to internal_macro const
[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::intrinsics::is_aligned_and_not_null;
5 use crate::mem;
6 use crate::ptr;
7
8 /// Forms a slice from a pointer and a length.
9 ///
10 /// The `len` argument is the number of **elements**, not the number of bytes.
11 ///
12 /// # Safety
13 ///
14 /// Behavior is undefined if any of the following conditions are violated:
15 ///
16 /// * `data` must be [valid] for reads for `len * mem::size_of::<T>()` many bytes,
17 ///   and it must be properly aligned. This means in particular:
18 ///
19 ///     * The entire memory range of this slice must be contained within a single allocated object!
20 ///       Slices can never span across multiple allocated objects. See [below](#incorrect-usage)
21 ///       for an example incorrectly not taking this into account.
22 ///     * `data` must be non-null and aligned even for zero-length slices. One
23 ///       reason for this is that enum layout optimizations may rely on references
24 ///       (including slices of any length) being aligned and non-null to distinguish
25 ///       them from other data. You can obtain a pointer that is usable as `data`
26 ///       for zero-length slices using [`NonNull::dangling()`].
27 ///
28 /// * `data` must point to `len` consecutive properly initialized values of type `T`.
29 ///
30 /// * The memory referenced by the returned slice must not be mutated for the duration
31 ///   of lifetime `'a`, except inside an `UnsafeCell`.
32 ///
33 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
34 ///   See the safety documentation of [`pointer::offset`].
35 ///
36 /// # Caveat
37 ///
38 /// The lifetime for the returned slice is inferred from its usage. To
39 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
40 /// source lifetime is safe in the context, such as by providing a helper
41 /// function taking the lifetime of a host value for the slice, or by explicit
42 /// annotation.
43 ///
44 /// # Examples
45 ///
46 /// ```
47 /// use std::slice;
48 ///
49 /// // manifest a slice for a single element
50 /// let x = 42;
51 /// let ptr = &x as *const _;
52 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
53 /// assert_eq!(slice[0], 42);
54 /// ```
55 ///
56 /// ### Incorrect usage
57 ///
58 /// The following `join_slices` function is **unsound** ⚠️
59 ///
60 /// ```rust,no_run
61 /// use std::slice;
62 ///
63 /// fn join_slices<'a, T>(fst: &'a [T], snd: &'a [T]) -> &'a [T] {
64 ///     let fst_end = fst.as_ptr().wrapping_add(fst.len());
65 ///     let snd_start = snd.as_ptr();
66 ///     assert_eq!(fst_end, snd_start, "Slices must be contiguous!");
67 ///     unsafe {
68 ///         // The assertion above ensures `fst` and `snd` are contiguous, but they might
69 ///         // still be contained within _different allocated objects_, in which case
70 ///         // creating this slice is undefined behavior.
71 ///         slice::from_raw_parts(fst.as_ptr(), fst.len() + snd.len())
72 ///     }
73 /// }
74 ///
75 /// fn main() {
76 ///     // `a` and `b` are different allocated objects...
77 ///     let a = 42;
78 ///     let b = 27;
79 ///     // ... which may nevertheless be laid out contiguously in memory: | a | b |
80 ///     let _ = join_slices(slice::from_ref(&a), slice::from_ref(&b)); // UB
81 /// }
82 /// ```
83 ///
84 /// [valid]: ptr#safety
85 /// [`NonNull::dangling()`]: ptr::NonNull::dangling
86 #[inline]
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
89     debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
90     debug_assert!(
91         mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
92         "attempt to create slice covering at least half the address space"
93     );
94     // SAFETY: the caller must uphold the safety contract for `from_raw_parts`.
95     unsafe { &*ptr::slice_from_raw_parts(data, len) }
96 }
97
98 /// Performs the same functionality as [`from_raw_parts`], except that a
99 /// mutable slice is returned.
100 ///
101 /// # Safety
102 ///
103 /// Behavior is undefined if any of the following conditions are violated:
104 ///
105 /// * `data` must be [valid] for both reads and writes for `len * mem::size_of::<T>()` many bytes,
106 ///   and it must be properly aligned. This means in particular:
107 ///
108 ///     * The entire memory range of this slice must be contained within a single allocated object!
109 ///       Slices can never span across multiple allocated objects.
110 ///     * `data` must be non-null and aligned even for zero-length slices. One
111 ///       reason for this is that enum layout optimizations may rely on references
112 ///       (including slices of any length) being aligned and non-null to distinguish
113 ///       them from other data. You can obtain a pointer that is usable as `data`
114 ///       for zero-length slices using [`NonNull::dangling()`].
115 ///
116 /// * `data` must point to `len` consecutive properly initialized values of type `T`.
117 ///
118 /// * The memory referenced by the returned slice must not be accessed through any other pointer
119 ///   (not derived from the return value) for the duration of lifetime `'a`.
120 ///   Both read and write accesses are forbidden.
121 ///
122 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
123 ///   See the safety documentation of [`pointer::offset`].
124 ///
125 /// [valid]: ptr#safety
126 /// [`NonNull::dangling()`]: ptr::NonNull::dangling
127 #[inline]
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
130     debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
131     debug_assert!(
132         mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
133         "attempt to create slice covering at least half the address space"
134     );
135     // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`.
136     unsafe { &mut *ptr::slice_from_raw_parts_mut(data, len) }
137 }
138
139 /// Converts a reference to T into a slice of length 1 (without copying).
140 #[stable(feature = "from_ref", since = "1.28.0")]
141 pub fn from_ref<T>(s: &T) -> &[T] {
142     array::from_ref(s)
143 }
144
145 /// Converts a reference to T into a slice of length 1 (without copying).
146 #[stable(feature = "from_ref", since = "1.28.0")]
147 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
148     array::from_mut(s)
149 }