]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/mod.rs
Merge commit '35d9c6bf256968e1b40e0d554607928bdf9cebea' into sync_cg_clif-2022-02-23
[rust.git] / library / core / src / ptr / mod.rs
1 //! Manually manage memory through raw pointers.
2 //!
3 //! *[See also the pointer primitive types](pointer).*
4 //!
5 //! # Safety
6 //!
7 //! Many functions in this module take raw pointers as arguments and read from
8 //! or write to them. For this to be safe, these pointers must be *valid*.
9 //! Whether a pointer is valid depends on the operation it is used for
10 //! (read or write), and the extent of the memory that is accessed (i.e.,
11 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
12 //! to access only a single value, in which case the documentation omits the size
13 //! and implicitly assumes it to be `size_of::<T>()` bytes.
14 //!
15 //! The precise rules for validity are not determined yet. The guarantees that are
16 //! provided at this point are very minimal:
17 //!
18 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
19 //! * For a pointer to be valid, it is necessary, but not always sufficient, that the pointer
20 //!   be *dereferenceable*: the memory range of the given size starting at the pointer must all be
21 //!   within the bounds of a single allocated object. Note that in Rust,
22 //!   every (stack-allocated) variable is considered a separate allocated object.
23 //! * Even for operations of [size zero][zst], the pointer must not be pointing to deallocated
24 //!   memory, i.e., deallocation makes pointers invalid even for zero-sized operations. However,
25 //!   casting any non-zero integer *literal* to a pointer is valid for zero-sized accesses, even if
26 //!   some memory happens to exist at that address and gets deallocated. This corresponds to writing
27 //!   your own allocator: allocating zero-sized objects is not very hard. The canonical way to
28 //!   obtain a pointer that is valid for zero-sized accesses is [`NonNull::dangling`].
29 //! * All accesses performed by functions in this module are *non-atomic* in the sense
30 //!   of [atomic operations] used to synchronize between threads. This means it is
31 //!   undefined behavior to perform two concurrent accesses to the same location from different
32 //!   threads unless both accesses only read from memory. Notice that this explicitly
33 //!   includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
34 //!   be used for inter-thread synchronization.
35 //! * The result of casting a reference to a pointer is valid for as long as the
36 //!   underlying object is live and no reference (just raw pointers) is used to
37 //!   access the same memory.
38 //!
39 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
40 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
41 //! will be provided eventually, as the [aliasing] rules are being determined. For more
42 //! information, see the [book] as well as the section in the reference devoted
43 //! to [undefined behavior][ub].
44 //!
45 //! ## Alignment
46 //!
47 //! Valid raw pointers as defined above are not necessarily properly aligned (where
48 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
49 //! aligned to `mem::align_of::<T>()`). However, most functions require their
50 //! arguments to be properly aligned, and will explicitly state
51 //! this requirement in their documentation. Notable exceptions to this are
52 //! [`read_unaligned`] and [`write_unaligned`].
53 //!
54 //! When a function requires proper alignment, it does so even if the access
55 //! has size 0, i.e., even if memory is not actually touched. Consider using
56 //! [`NonNull::dangling`] in such cases.
57 //!
58 //! ## Allocated object
59 //!
60 //! For several operations, such as [`offset`] or field projections (`expr.field`), the notion of an
61 //! "allocated object" becomes relevant. An allocated object is a contiguous region of memory.
62 //! Common examples of allocated objects include stack-allocated variables (each variable is a
63 //! separate allocated object), heap allocations (each allocation created by the global allocator is
64 //! a separate allocated object), and `static` variables.
65 //!
66 //! [aliasing]: ../../nomicon/aliasing.html
67 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
68 //! [ub]: ../../reference/behavior-considered-undefined.html
69 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
70 //! [atomic operations]: crate::sync::atomic
71 //! [`offset`]: pointer::offset
72
73 #![stable(feature = "rust1", since = "1.0.0")]
74
75 use crate::cmp::Ordering;
76 use crate::fmt;
77 use crate::hash;
78 use crate::intrinsics::{self, abort, is_aligned_and_not_null};
79 use crate::mem::{self, MaybeUninit};
80
81 #[stable(feature = "rust1", since = "1.0.0")]
82 #[doc(inline)]
83 pub use crate::intrinsics::copy_nonoverlapping;
84
85 #[stable(feature = "rust1", since = "1.0.0")]
86 #[doc(inline)]
87 pub use crate::intrinsics::copy;
88
89 #[stable(feature = "rust1", since = "1.0.0")]
90 #[doc(inline)]
91 pub use crate::intrinsics::write_bytes;
92
93 mod metadata;
94 pub(crate) use metadata::PtrRepr;
95 #[unstable(feature = "ptr_metadata", issue = "81513")]
96 pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin};
97
98 mod non_null;
99 #[stable(feature = "nonnull", since = "1.25.0")]
100 pub use non_null::NonNull;
101
102 mod unique;
103 #[unstable(feature = "ptr_internals", issue = "none")]
104 pub use unique::Unique;
105
106 mod const_ptr;
107 mod mut_ptr;
108
109 /// Executes the destructor (if any) of the pointed-to value.
110 ///
111 /// This is semantically equivalent to calling [`ptr::read`] and discarding
112 /// the result, but has the following advantages:
113 ///
114 /// * It is *required* to use `drop_in_place` to drop unsized types like
115 ///   trait objects, because they can't be read out onto the stack and
116 ///   dropped normally.
117 ///
118 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
119 ///   dropping manually allocated memory (e.g., in the implementations of
120 ///   `Box`/`Rc`/`Vec`), as the compiler doesn't need to prove that it's
121 ///   sound to elide the copy.
122 ///
123 /// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
124 ///   (pinned data must not be moved before it is dropped).
125 ///
126 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
127 /// location first using [`ptr::read_unaligned`]. For packed structs, this move is
128 /// done automatically by the compiler. This means the fields of packed structs
129 /// are not dropped in-place.
130 ///
131 /// [`ptr::read`]: self::read
132 /// [`ptr::read_unaligned`]: self::read_unaligned
133 /// [pinned]: crate::pin
134 ///
135 /// # Safety
136 ///
137 /// Behavior is undefined if any of the following conditions are violated:
138 ///
139 /// * `to_drop` must be [valid] for both reads and writes.
140 ///
141 /// * `to_drop` must be properly aligned.
142 ///
143 /// * The value `to_drop` points to must be valid for dropping, which may mean it must uphold
144 ///   additional invariants - this is type-dependent.
145 ///
146 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
147 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
148 /// foo` counts as a use because it will cause the value to be dropped
149 /// again. [`write()`] can be used to overwrite data without causing it to be
150 /// dropped.
151 ///
152 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
153 ///
154 /// [valid]: self#safety
155 ///
156 /// # Examples
157 ///
158 /// Manually remove the last item from a vector:
159 ///
160 /// ```
161 /// use std::ptr;
162 /// use std::rc::Rc;
163 ///
164 /// let last = Rc::new(1);
165 /// let weak = Rc::downgrade(&last);
166 ///
167 /// let mut v = vec![Rc::new(0), last];
168 ///
169 /// unsafe {
170 ///     // Get a raw pointer to the last element in `v`.
171 ///     let ptr = &mut v[1] as *mut _;
172 ///     // Shorten `v` to prevent the last item from being dropped. We do that first,
173 ///     // to prevent issues if the `drop_in_place` below panics.
174 ///     v.set_len(1);
175 ///     // Without a call `drop_in_place`, the last item would never be dropped,
176 ///     // and the memory it manages would be leaked.
177 ///     ptr::drop_in_place(ptr);
178 /// }
179 ///
180 /// assert_eq!(v, &[0.into()]);
181 ///
182 /// // Ensure that the last item was dropped.
183 /// assert!(weak.upgrade().is_none());
184 /// ```
185 #[stable(feature = "drop_in_place", since = "1.8.0")]
186 #[lang = "drop_in_place"]
187 #[allow(unconditional_recursion)]
188 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
189     // Code here does not matter - this is replaced by the
190     // real drop glue by the compiler.
191
192     // SAFETY: see comment above
193     unsafe { drop_in_place(to_drop) }
194 }
195
196 /// Creates a null raw pointer.
197 ///
198 /// # Examples
199 ///
200 /// ```
201 /// use std::ptr;
202 ///
203 /// let p: *const i32 = ptr::null();
204 /// assert!(p.is_null());
205 /// ```
206 #[inline(always)]
207 #[must_use]
208 #[stable(feature = "rust1", since = "1.0.0")]
209 #[rustc_promotable]
210 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
211 #[rustc_diagnostic_item = "ptr_null"]
212 pub const fn null<T>() -> *const T {
213     0 as *const T
214 }
215
216 /// Creates a null mutable raw pointer.
217 ///
218 /// # Examples
219 ///
220 /// ```
221 /// use std::ptr;
222 ///
223 /// let p: *mut i32 = ptr::null_mut();
224 /// assert!(p.is_null());
225 /// ```
226 #[inline(always)]
227 #[must_use]
228 #[stable(feature = "rust1", since = "1.0.0")]
229 #[rustc_promotable]
230 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
231 #[rustc_diagnostic_item = "ptr_null_mut"]
232 pub const fn null_mut<T>() -> *mut T {
233     0 as *mut T
234 }
235
236 /// Forms a raw slice from a pointer and a length.
237 ///
238 /// The `len` argument is the number of **elements**, not the number of bytes.
239 ///
240 /// This function is safe, but actually using the return value is unsafe.
241 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
242 ///
243 /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
244 ///
245 /// # Examples
246 ///
247 /// ```rust
248 /// use std::ptr;
249 ///
250 /// // create a slice pointer when starting out with a pointer to the first element
251 /// let x = [5, 6, 7];
252 /// let raw_pointer = x.as_ptr();
253 /// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
254 /// assert_eq!(unsafe { &*slice }[2], 7);
255 /// ```
256 #[inline]
257 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
258 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
259 pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
260     from_raw_parts(data.cast(), len)
261 }
262
263 /// Performs the same functionality as [`slice_from_raw_parts`], except that a
264 /// raw mutable slice is returned, as opposed to a raw immutable slice.
265 ///
266 /// See the documentation of [`slice_from_raw_parts`] for more details.
267 ///
268 /// This function is safe, but actually using the return value is unsafe.
269 /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
270 ///
271 /// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
272 ///
273 /// # Examples
274 ///
275 /// ```rust
276 /// use std::ptr;
277 ///
278 /// let x = &mut [5, 6, 7];
279 /// let raw_pointer = x.as_mut_ptr();
280 /// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
281 ///
282 /// unsafe {
283 ///     (*slice)[2] = 99; // assign a value at an index in the slice
284 /// };
285 ///
286 /// assert_eq!(unsafe { &*slice }[2], 99);
287 /// ```
288 #[inline]
289 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
290 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
291 pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
292     from_raw_parts_mut(data.cast(), len)
293 }
294
295 /// Swaps the values at two mutable locations of the same type, without
296 /// deinitializing either.
297 ///
298 /// But for the following two exceptions, this function is semantically
299 /// equivalent to [`mem::swap`]:
300 ///
301 /// * It operates on raw pointers instead of references. When references are
302 ///   available, [`mem::swap`] should be preferred.
303 ///
304 /// * The two pointed-to values may overlap. If the values do overlap, then the
305 ///   overlapping region of memory from `x` will be used. This is demonstrated
306 ///   in the second example below.
307 ///
308 /// # Safety
309 ///
310 /// Behavior is undefined if any of the following conditions are violated:
311 ///
312 /// * Both `x` and `y` must be [valid] for both reads and writes.
313 ///
314 /// * Both `x` and `y` must be properly aligned.
315 ///
316 /// Note that even if `T` has size `0`, the pointers must be non-null and properly aligned.
317 ///
318 /// [valid]: self#safety
319 ///
320 /// # Examples
321 ///
322 /// Swapping two non-overlapping regions:
323 ///
324 /// ```
325 /// use std::ptr;
326 ///
327 /// let mut array = [0, 1, 2, 3];
328 ///
329 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
330 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
331 ///
332 /// unsafe {
333 ///     ptr::swap(x, y);
334 ///     assert_eq!([2, 3, 0, 1], array);
335 /// }
336 /// ```
337 ///
338 /// Swapping two overlapping regions:
339 ///
340 /// ```
341 /// use std::ptr;
342 ///
343 /// let mut array: [i32; 4] = [0, 1, 2, 3];
344 ///
345 /// let array_ptr: *mut i32 = array.as_mut_ptr();
346 ///
347 /// let x = array_ptr as *mut [i32; 3]; // this is `array[0..3]`
348 /// let y = unsafe { array_ptr.add(1) } as *mut [i32; 3]; // this is `array[1..4]`
349 ///
350 /// unsafe {
351 ///     ptr::swap(x, y);
352 ///     // The indices `1..3` of the slice overlap between `x` and `y`.
353 ///     // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
354 ///     // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
355 ///     // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
356 ///     // This implementation is defined to make the latter choice.
357 ///     assert_eq!([1, 0, 1, 2], array);
358 /// }
359 /// ```
360 #[inline]
361 #[stable(feature = "rust1", since = "1.0.0")]
362 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
363 pub const unsafe fn swap<T>(x: *mut T, y: *mut T) {
364     // Give ourselves some scratch space to work with.
365     // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
366     let mut tmp = MaybeUninit::<T>::uninit();
367
368     // Perform the swap
369     // SAFETY: the caller must guarantee that `x` and `y` are
370     // valid for writes and properly aligned. `tmp` cannot be
371     // overlapping either `x` or `y` because `tmp` was just allocated
372     // on the stack as a separate allocated object.
373     unsafe {
374         copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
375         copy(y, x, 1); // `x` and `y` may overlap
376         copy_nonoverlapping(tmp.as_ptr(), y, 1);
377     }
378 }
379
380 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
381 /// beginning at `x` and `y`. The two regions must *not* overlap.
382 ///
383 /// # Safety
384 ///
385 /// Behavior is undefined if any of the following conditions are violated:
386 ///
387 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
388 ///   size_of::<T>()` bytes.
389 ///
390 /// * Both `x` and `y` must be properly aligned.
391 ///
392 /// * The region of memory beginning at `x` with a size of `count *
393 ///   size_of::<T>()` bytes must *not* overlap with the region of memory
394 ///   beginning at `y` with the same size.
395 ///
396 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
397 /// the pointers must be non-null and properly aligned.
398 ///
399 /// [valid]: self#safety
400 ///
401 /// # Examples
402 ///
403 /// Basic usage:
404 ///
405 /// ```
406 /// use std::ptr;
407 ///
408 /// let mut x = [1, 2, 3, 4];
409 /// let mut y = [7, 8, 9];
410 ///
411 /// unsafe {
412 ///     ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
413 /// }
414 ///
415 /// assert_eq!(x, [7, 8, 3, 4]);
416 /// assert_eq!(y, [1, 2, 9]);
417 /// ```
418 #[inline]
419 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
420 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
421 pub const unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
422     let x = x as *mut u8;
423     let y = y as *mut u8;
424     let len = mem::size_of::<T>() * count;
425     // SAFETY: the caller must guarantee that `x` and `y` are
426     // valid for writes and properly aligned.
427     unsafe { swap_nonoverlapping_bytes(x, y, len) }
428 }
429
430 #[inline]
431 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
432 pub(crate) const unsafe fn swap_nonoverlapping_one<T>(x: *mut T, y: *mut T) {
433     // NOTE(eddyb) SPIR-V's Logical addressing model doesn't allow for arbitrary
434     // reinterpretation of values as (chunkable) byte arrays, and the loop in the
435     // block optimization in `swap_nonoverlapping_bytes` is hard to rewrite back
436     // into the (unoptimized) direct swapping implementation, so we disable it.
437     // FIXME(eddyb) the block optimization also prevents MIR optimizations from
438     // understanding `mem::replace`, `Option::take`, etc. - a better overall
439     // solution might be to make `swap_nonoverlapping` into an intrinsic, which
440     // a backend can choose to implement using the block optimization, or not.
441     #[cfg(not(target_arch = "spirv"))]
442     {
443         // Only apply the block optimization in `swap_nonoverlapping_bytes` for types
444         // at least as large as the block size, to avoid pessimizing codegen.
445         if mem::size_of::<T>() >= 32 {
446             // SAFETY: the caller must uphold the safety contract for `swap_nonoverlapping`.
447             unsafe { swap_nonoverlapping(x, y, 1) };
448             return;
449         }
450     }
451
452     // Direct swapping, for the cases not going through the block optimization.
453     // SAFETY: the caller must guarantee that `x` and `y` are valid
454     // for writes, properly aligned, and non-overlapping.
455     unsafe {
456         let z = read(x);
457         copy_nonoverlapping(y, x, 1);
458         write(y, z);
459     }
460 }
461
462 #[inline]
463 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
464 const unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
465     // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
466     // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
467     // Haswell E processors. LLVM is more able to optimize if we give a struct a
468     // #[repr(simd)], even if we don't actually use this struct directly.
469     //
470     // FIXME repr(simd) broken on emscripten and redox
471     #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))]
472     struct Block(u64, u64, u64, u64);
473     struct UnalignedBlock(u64, u64, u64, u64);
474
475     let block_size = mem::size_of::<Block>();
476
477     // Loop through x & y, copying them `Block` at a time
478     // The optimizer should unroll the loop fully for most types
479     // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
480     let mut i = 0;
481     while i + block_size <= len {
482         // Create some uninitialized memory as scratch space
483         // Declaring `t` here avoids aligning the stack when this loop is unused
484         let mut t = mem::MaybeUninit::<Block>::uninit();
485         let t = t.as_mut_ptr() as *mut u8;
486
487         // SAFETY: As `i < len`, and as the caller must guarantee that `x` and `y` are valid
488         // for `len` bytes, `x + i` and `y + i` must be valid addresses, which fulfills the
489         // safety contract for `add`.
490         //
491         // Also, the caller must guarantee that `x` and `y` are valid for writes, properly aligned,
492         // and non-overlapping, which fulfills the safety contract for `copy_nonoverlapping`.
493         unsafe {
494             let x = x.add(i);
495             let y = y.add(i);
496
497             // Swap a block of bytes of x & y, using t as a temporary buffer
498             // This should be optimized into efficient SIMD operations where available
499             copy_nonoverlapping(x, t, block_size);
500             copy_nonoverlapping(y, x, block_size);
501             copy_nonoverlapping(t, y, block_size);
502         }
503         i += block_size;
504     }
505
506     if i < len {
507         // Swap any remaining bytes
508         let mut t = mem::MaybeUninit::<UnalignedBlock>::uninit();
509         let rem = len - i;
510
511         let t = t.as_mut_ptr() as *mut u8;
512
513         // SAFETY: see previous safety comment.
514         unsafe {
515             let x = x.add(i);
516             let y = y.add(i);
517
518             copy_nonoverlapping(x, t, rem);
519             copy_nonoverlapping(y, x, rem);
520             copy_nonoverlapping(t, y, rem);
521         }
522     }
523 }
524
525 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
526 ///
527 /// Neither value is dropped.
528 ///
529 /// This function is semantically equivalent to [`mem::replace`] except that it
530 /// operates on raw pointers instead of references. When references are
531 /// available, [`mem::replace`] should be preferred.
532 ///
533 /// # Safety
534 ///
535 /// Behavior is undefined if any of the following conditions are violated:
536 ///
537 /// * `dst` must be [valid] for both reads and writes.
538 ///
539 /// * `dst` must be properly aligned.
540 ///
541 /// * `dst` must point to a properly initialized value of type `T`.
542 ///
543 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
544 ///
545 /// [valid]: self#safety
546 ///
547 /// # Examples
548 ///
549 /// ```
550 /// use std::ptr;
551 ///
552 /// let mut rust = vec!['b', 'u', 's', 't'];
553 ///
554 /// // `mem::replace` would have the same effect without requiring the unsafe
555 /// // block.
556 /// let b = unsafe {
557 ///     ptr::replace(&mut rust[0], 'r')
558 /// };
559 ///
560 /// assert_eq!(b, 'b');
561 /// assert_eq!(rust, &['r', 'u', 's', 't']);
562 /// ```
563 #[inline]
564 #[stable(feature = "rust1", since = "1.0.0")]
565 #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
566 pub const unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
567     // SAFETY: the caller must guarantee that `dst` is valid to be
568     // cast to a mutable reference (valid for writes, aligned, initialized),
569     // and cannot overlap `src` since `dst` must point to a distinct
570     // allocated object.
571     unsafe {
572         mem::swap(&mut *dst, &mut src); // cannot overlap
573     }
574     src
575 }
576
577 /// Reads the value from `src` without moving it. This leaves the
578 /// memory in `src` unchanged.
579 ///
580 /// # Safety
581 ///
582 /// Behavior is undefined if any of the following conditions are violated:
583 ///
584 /// * `src` must be [valid] for reads.
585 ///
586 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
587 ///   case.
588 ///
589 /// * `src` must point to a properly initialized value of type `T`.
590 ///
591 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
592 ///
593 /// # Examples
594 ///
595 /// Basic usage:
596 ///
597 /// ```
598 /// let x = 12;
599 /// let y = &x as *const i32;
600 ///
601 /// unsafe {
602 ///     assert_eq!(std::ptr::read(y), 12);
603 /// }
604 /// ```
605 ///
606 /// Manually implement [`mem::swap`]:
607 ///
608 /// ```
609 /// use std::ptr;
610 ///
611 /// fn swap<T>(a: &mut T, b: &mut T) {
612 ///     unsafe {
613 ///         // Create a bitwise copy of the value at `a` in `tmp`.
614 ///         let tmp = ptr::read(a);
615 ///
616 ///         // Exiting at this point (either by explicitly returning or by
617 ///         // calling a function which panics) would cause the value in `tmp` to
618 ///         // be dropped while the same value is still referenced by `a`. This
619 ///         // could trigger undefined behavior if `T` is not `Copy`.
620 ///
621 ///         // Create a bitwise copy of the value at `b` in `a`.
622 ///         // This is safe because mutable references cannot alias.
623 ///         ptr::copy_nonoverlapping(b, a, 1);
624 ///
625 ///         // As above, exiting here could trigger undefined behavior because
626 ///         // the same value is referenced by `a` and `b`.
627 ///
628 ///         // Move `tmp` into `b`.
629 ///         ptr::write(b, tmp);
630 ///
631 ///         // `tmp` has been moved (`write` takes ownership of its second argument),
632 ///         // so nothing is dropped implicitly here.
633 ///     }
634 /// }
635 ///
636 /// let mut foo = "foo".to_owned();
637 /// let mut bar = "bar".to_owned();
638 ///
639 /// swap(&mut foo, &mut bar);
640 ///
641 /// assert_eq!(foo, "bar");
642 /// assert_eq!(bar, "foo");
643 /// ```
644 ///
645 /// ## Ownership of the Returned Value
646 ///
647 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
648 /// If `T` is not [`Copy`], using both the returned value and the value at
649 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
650 /// use because it will attempt to drop the value at `*src`.
651 ///
652 /// [`write()`] can be used to overwrite data without causing it to be dropped.
653 ///
654 /// ```
655 /// use std::ptr;
656 ///
657 /// let mut s = String::from("foo");
658 /// unsafe {
659 ///     // `s2` now points to the same underlying memory as `s`.
660 ///     let mut s2: String = ptr::read(&s);
661 ///
662 ///     assert_eq!(s2, "foo");
663 ///
664 ///     // Assigning to `s2` causes its original value to be dropped. Beyond
665 ///     // this point, `s` must no longer be used, as the underlying memory has
666 ///     // been freed.
667 ///     s2 = String::default();
668 ///     assert_eq!(s2, "");
669 ///
670 ///     // Assigning to `s` would cause the old value to be dropped again,
671 ///     // resulting in undefined behavior.
672 ///     // s = String::from("bar"); // ERROR
673 ///
674 ///     // `ptr::write` can be used to overwrite a value without dropping it.
675 ///     ptr::write(&mut s, String::from("bar"));
676 /// }
677 ///
678 /// assert_eq!(s, "bar");
679 /// ```
680 ///
681 /// [valid]: self#safety
682 #[inline]
683 #[stable(feature = "rust1", since = "1.0.0")]
684 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
685 pub const unsafe fn read<T>(src: *const T) -> T {
686     // We are calling the intrinsics directly to avoid function calls in the generated code
687     // as `intrinsics::copy_nonoverlapping` is a wrapper function.
688     extern "rust-intrinsic" {
689         #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
690         fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
691     }
692
693     let mut tmp = MaybeUninit::<T>::uninit();
694     // SAFETY: the caller must guarantee that `src` is valid for reads.
695     // `src` cannot overlap `tmp` because `tmp` was just allocated on
696     // the stack as a separate allocated object.
697     //
698     // Also, since we just wrote a valid value into `tmp`, it is guaranteed
699     // to be properly initialized.
700     unsafe {
701         copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
702         tmp.assume_init()
703     }
704 }
705
706 /// Reads the value from `src` without moving it. This leaves the
707 /// memory in `src` unchanged.
708 ///
709 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
710 ///
711 /// # Safety
712 ///
713 /// Behavior is undefined if any of the following conditions are violated:
714 ///
715 /// * `src` must be [valid] for reads.
716 ///
717 /// * `src` must point to a properly initialized value of type `T`.
718 ///
719 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
720 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
721 /// value and the value at `*src` can [violate memory safety][read-ownership].
722 ///
723 /// Note that even if `T` has size `0`, the pointer must be non-null.
724 ///
725 /// [read-ownership]: read#ownership-of-the-returned-value
726 /// [valid]: self#safety
727 ///
728 /// ## On `packed` structs
729 ///
730 /// Attempting to create a raw pointer to an `unaligned` struct field with
731 /// an expression such as `&packed.unaligned as *const FieldType` creates an
732 /// intermediate unaligned reference before converting that to a raw pointer.
733 /// That this reference is temporary and immediately cast is inconsequential
734 /// as the compiler always expects references to be properly aligned.
735 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
736 /// *undefined behavior* in your program.
737 ///
738 /// Instead you must use the [`ptr::addr_of!`](addr_of) macro to
739 /// create the pointer. You may use that returned pointer together with this
740 /// function.
741 ///
742 /// An example of what not to do and how this relates to `read_unaligned` is:
743 ///
744 /// ```
745 /// #[repr(packed, C)]
746 /// struct Packed {
747 ///     _padding: u8,
748 ///     unaligned: u32,
749 /// }
750 ///
751 /// let packed = Packed {
752 ///     _padding: 0x00,
753 ///     unaligned: 0x01020304,
754 /// };
755 ///
756 /// // Take the address of a 32-bit integer which is not aligned.
757 /// // In contrast to `&packed.unaligned as *const _`, this has no undefined behavior.
758 /// let unaligned = std::ptr::addr_of!(packed.unaligned);
759 ///
760 /// let v = unsafe { std::ptr::read_unaligned(unaligned) };
761 /// assert_eq!(v, 0x01020304);
762 /// ```
763 ///
764 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
765 ///
766 /// # Examples
767 ///
768 /// Read a usize value from a byte buffer:
769 ///
770 /// ```
771 /// use std::mem;
772 ///
773 /// fn read_usize(x: &[u8]) -> usize {
774 ///     assert!(x.len() >= mem::size_of::<usize>());
775 ///
776 ///     let ptr = x.as_ptr() as *const usize;
777 ///
778 ///     unsafe { ptr.read_unaligned() }
779 /// }
780 /// ```
781 #[inline]
782 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
783 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
784 pub const unsafe fn read_unaligned<T>(src: *const T) -> T {
785     let mut tmp = MaybeUninit::<T>::uninit();
786     // SAFETY: the caller must guarantee that `src` is valid for reads.
787     // `src` cannot overlap `tmp` because `tmp` was just allocated on
788     // the stack as a separate allocated object.
789     //
790     // Also, since we just wrote a valid value into `tmp`, it is guaranteed
791     // to be properly initialized.
792     unsafe {
793         copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::<T>());
794         tmp.assume_init()
795     }
796 }
797
798 /// Overwrites a memory location with the given value without reading or
799 /// dropping the old value.
800 ///
801 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
802 /// allocations or resources, so care should be taken not to overwrite an object
803 /// that should be dropped.
804 ///
805 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
806 /// location pointed to by `dst`.
807 ///
808 /// This is appropriate for initializing uninitialized memory, or overwriting
809 /// memory that has previously been [`read`] from.
810 ///
811 /// # Safety
812 ///
813 /// Behavior is undefined if any of the following conditions are violated:
814 ///
815 /// * `dst` must be [valid] for writes.
816 ///
817 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
818 ///   case.
819 ///
820 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
821 ///
822 /// [valid]: self#safety
823 ///
824 /// # Examples
825 ///
826 /// Basic usage:
827 ///
828 /// ```
829 /// let mut x = 0;
830 /// let y = &mut x as *mut i32;
831 /// let z = 12;
832 ///
833 /// unsafe {
834 ///     std::ptr::write(y, z);
835 ///     assert_eq!(std::ptr::read(y), 12);
836 /// }
837 /// ```
838 ///
839 /// Manually implement [`mem::swap`]:
840 ///
841 /// ```
842 /// use std::ptr;
843 ///
844 /// fn swap<T>(a: &mut T, b: &mut T) {
845 ///     unsafe {
846 ///         // Create a bitwise copy of the value at `a` in `tmp`.
847 ///         let tmp = ptr::read(a);
848 ///
849 ///         // Exiting at this point (either by explicitly returning or by
850 ///         // calling a function which panics) would cause the value in `tmp` to
851 ///         // be dropped while the same value is still referenced by `a`. This
852 ///         // could trigger undefined behavior if `T` is not `Copy`.
853 ///
854 ///         // Create a bitwise copy of the value at `b` in `a`.
855 ///         // This is safe because mutable references cannot alias.
856 ///         ptr::copy_nonoverlapping(b, a, 1);
857 ///
858 ///         // As above, exiting here could trigger undefined behavior because
859 ///         // the same value is referenced by `a` and `b`.
860 ///
861 ///         // Move `tmp` into `b`.
862 ///         ptr::write(b, tmp);
863 ///
864 ///         // `tmp` has been moved (`write` takes ownership of its second argument),
865 ///         // so nothing is dropped implicitly here.
866 ///     }
867 /// }
868 ///
869 /// let mut foo = "foo".to_owned();
870 /// let mut bar = "bar".to_owned();
871 ///
872 /// swap(&mut foo, &mut bar);
873 ///
874 /// assert_eq!(foo, "bar");
875 /// assert_eq!(bar, "foo");
876 /// ```
877 #[inline]
878 #[stable(feature = "rust1", since = "1.0.0")]
879 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
880 pub const unsafe fn write<T>(dst: *mut T, src: T) {
881     // We are calling the intrinsics directly to avoid function calls in the generated code
882     // as `intrinsics::copy_nonoverlapping` is a wrapper function.
883     extern "rust-intrinsic" {
884         #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
885         fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
886     }
887
888     // SAFETY: the caller must guarantee that `dst` is valid for writes.
889     // `dst` cannot overlap `src` because the caller has mutable access
890     // to `dst` while `src` is owned by this function.
891     unsafe {
892         copy_nonoverlapping(&src as *const T, dst, 1);
893         intrinsics::forget(src);
894     }
895 }
896
897 /// Overwrites a memory location with the given value without reading or
898 /// dropping the old value.
899 ///
900 /// Unlike [`write()`], the pointer may be unaligned.
901 ///
902 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
903 /// could leak allocations or resources, so care should be taken not to overwrite
904 /// an object that should be dropped.
905 ///
906 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
907 /// location pointed to by `dst`.
908 ///
909 /// This is appropriate for initializing uninitialized memory, or overwriting
910 /// memory that has previously been read with [`read_unaligned`].
911 ///
912 /// # Safety
913 ///
914 /// Behavior is undefined if any of the following conditions are violated:
915 ///
916 /// * `dst` must be [valid] for writes.
917 ///
918 /// Note that even if `T` has size `0`, the pointer must be non-null.
919 ///
920 /// [valid]: self#safety
921 ///
922 /// ## On `packed` structs
923 ///
924 /// Attempting to create a raw pointer to an `unaligned` struct field with
925 /// an expression such as `&packed.unaligned as *const FieldType` creates an
926 /// intermediate unaligned reference before converting that to a raw pointer.
927 /// That this reference is temporary and immediately cast is inconsequential
928 /// as the compiler always expects references to be properly aligned.
929 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
930 /// *undefined behavior* in your program.
931 ///
932 /// Instead you must use the [`ptr::addr_of_mut!`](addr_of_mut)
933 /// macro to create the pointer. You may use that returned pointer together with
934 /// this function.
935 ///
936 /// An example of how to do it and how this relates to `write_unaligned` is:
937 ///
938 /// ```
939 /// #[repr(packed, C)]
940 /// struct Packed {
941 ///     _padding: u8,
942 ///     unaligned: u32,
943 /// }
944 ///
945 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
946 ///
947 /// // Take the address of a 32-bit integer which is not aligned.
948 /// // In contrast to `&packed.unaligned as *mut _`, this has no undefined behavior.
949 /// let unaligned = std::ptr::addr_of_mut!(packed.unaligned);
950 ///
951 /// unsafe { std::ptr::write_unaligned(unaligned, 42) };
952 ///
953 /// assert_eq!({packed.unaligned}, 42); // `{...}` forces copying the field instead of creating a reference.
954 /// ```
955 ///
956 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however
957 /// (as can be seen in the `assert_eq!` above).
958 ///
959 /// # Examples
960 ///
961 /// Write a usize value to a byte buffer:
962 ///
963 /// ```
964 /// use std::mem;
965 ///
966 /// fn write_usize(x: &mut [u8], val: usize) {
967 ///     assert!(x.len() >= mem::size_of::<usize>());
968 ///
969 ///     let ptr = x.as_mut_ptr() as *mut usize;
970 ///
971 ///     unsafe { ptr.write_unaligned(val) }
972 /// }
973 /// ```
974 #[inline]
975 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
976 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
977 pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
978     // SAFETY: the caller must guarantee that `dst` is valid for writes.
979     // `dst` cannot overlap `src` because the caller has mutable access
980     // to `dst` while `src` is owned by this function.
981     unsafe {
982         copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::<T>());
983         // We are calling the intrinsic directly to avoid function calls in the generated code.
984         intrinsics::forget(src);
985     }
986 }
987
988 /// Performs a volatile read of the value from `src` without moving it. This
989 /// leaves the memory in `src` unchanged.
990 ///
991 /// Volatile operations are intended to act on I/O memory, and are guaranteed
992 /// to not be elided or reordered by the compiler across other volatile
993 /// operations.
994 ///
995 /// # Notes
996 ///
997 /// Rust does not currently have a rigorously and formally defined memory model,
998 /// so the precise semantics of what "volatile" means here is subject to change
999 /// over time. That being said, the semantics will almost always end up pretty
1000 /// similar to [C11's definition of volatile][c11].
1001 ///
1002 /// The compiler shouldn't change the relative order or number of volatile
1003 /// memory operations. However, volatile memory operations on zero-sized types
1004 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
1005 /// and may be ignored.
1006 ///
1007 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1008 ///
1009 /// # Safety
1010 ///
1011 /// Behavior is undefined if any of the following conditions are violated:
1012 ///
1013 /// * `src` must be [valid] for reads.
1014 ///
1015 /// * `src` must be properly aligned.
1016 ///
1017 /// * `src` must point to a properly initialized value of type `T`.
1018 ///
1019 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
1020 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1021 /// value and the value at `*src` can [violate memory safety][read-ownership].
1022 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
1023 /// incorrect.
1024 ///
1025 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1026 ///
1027 /// [valid]: self#safety
1028 /// [read-ownership]: read#ownership-of-the-returned-value
1029 ///
1030 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1031 /// on questions involving concurrent access from multiple threads. Volatile
1032 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1033 /// a race between a `read_volatile` and any write operation to the same location
1034 /// is undefined behavior.
1035 ///
1036 /// # Examples
1037 ///
1038 /// Basic usage:
1039 ///
1040 /// ```
1041 /// let x = 12;
1042 /// let y = &x as *const i32;
1043 ///
1044 /// unsafe {
1045 ///     assert_eq!(std::ptr::read_volatile(y), 12);
1046 /// }
1047 /// ```
1048 #[inline]
1049 #[stable(feature = "volatile", since = "1.9.0")]
1050 pub unsafe fn read_volatile<T>(src: *const T) -> T {
1051     if cfg!(debug_assertions) && !is_aligned_and_not_null(src) {
1052         // Not panicking to keep codegen impact smaller.
1053         abort();
1054     }
1055     // SAFETY: the caller must uphold the safety contract for `volatile_load`.
1056     unsafe { intrinsics::volatile_load(src) }
1057 }
1058
1059 /// Performs a volatile write of a memory location with the given value without
1060 /// reading or dropping the old value.
1061 ///
1062 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1063 /// to not be elided or reordered by the compiler across other volatile
1064 /// operations.
1065 ///
1066 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
1067 /// could leak allocations or resources, so care should be taken not to overwrite
1068 /// an object that should be dropped.
1069 ///
1070 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1071 /// location pointed to by `dst`.
1072 ///
1073 /// # Notes
1074 ///
1075 /// Rust does not currently have a rigorously and formally defined memory model,
1076 /// so the precise semantics of what "volatile" means here is subject to change
1077 /// over time. That being said, the semantics will almost always end up pretty
1078 /// similar to [C11's definition of volatile][c11].
1079 ///
1080 /// The compiler shouldn't change the relative order or number of volatile
1081 /// memory operations. However, volatile memory operations on zero-sized types
1082 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
1083 /// and may be ignored.
1084 ///
1085 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1086 ///
1087 /// # Safety
1088 ///
1089 /// Behavior is undefined if any of the following conditions are violated:
1090 ///
1091 /// * `dst` must be [valid] for writes.
1092 ///
1093 /// * `dst` must be properly aligned.
1094 ///
1095 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1096 ///
1097 /// [valid]: self#safety
1098 ///
1099 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1100 /// on questions involving concurrent access from multiple threads. Volatile
1101 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1102 /// a race between a `write_volatile` and any other operation (reading or writing)
1103 /// on the same location is undefined behavior.
1104 ///
1105 /// # Examples
1106 ///
1107 /// Basic usage:
1108 ///
1109 /// ```
1110 /// let mut x = 0;
1111 /// let y = &mut x as *mut i32;
1112 /// let z = 12;
1113 ///
1114 /// unsafe {
1115 ///     std::ptr::write_volatile(y, z);
1116 ///     assert_eq!(std::ptr::read_volatile(y), 12);
1117 /// }
1118 /// ```
1119 #[inline]
1120 #[stable(feature = "volatile", since = "1.9.0")]
1121 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
1122     if cfg!(debug_assertions) && !is_aligned_and_not_null(dst) {
1123         // Not panicking to keep codegen impact smaller.
1124         abort();
1125     }
1126     // SAFETY: the caller must uphold the safety contract for `volatile_store`.
1127     unsafe {
1128         intrinsics::volatile_store(dst, src);
1129     }
1130 }
1131
1132 /// Align pointer `p`.
1133 ///
1134 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
1135 /// to pointer `p` so that pointer `p` would get aligned to `a`.
1136 ///
1137 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
1138 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
1139 /// constants.
1140 ///
1141 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
1142 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
1143 /// than trying to adapt this to accommodate that change.
1144 ///
1145 /// Any questions go to @nagisa.
1146 #[lang = "align_offset"]
1147 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
1148     // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
1149     // 1, where the method versions of these operations are not inlined.
1150     use intrinsics::{
1151         unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub,
1152     };
1153
1154     /// Calculate multiplicative modular inverse of `x` modulo `m`.
1155     ///
1156     /// This implementation is tailored for `align_offset` and has following preconditions:
1157     ///
1158     /// * `m` is a power-of-two;
1159     /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1160     ///
1161     /// Implementation of this function shall not panic. Ever.
1162     #[inline]
1163     unsafe fn mod_inv(x: usize, m: usize) -> usize {
1164         /// Multiplicative modular inverse table modulo 2⁴ = 16.
1165         ///
1166         /// Note, that this table does not contain values where inverse does not exist (i.e., for
1167         /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
1168         const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
1169         /// Modulo for which the `INV_TABLE_MOD_16` is intended.
1170         const INV_TABLE_MOD: usize = 16;
1171         /// INV_TABLE_MOD²
1172         const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
1173
1174         let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
1175         // SAFETY: `m` is required to be a power-of-two, hence non-zero.
1176         let m_minus_one = unsafe { unchecked_sub(m, 1) };
1177         if m <= INV_TABLE_MOD {
1178             table_inverse & m_minus_one
1179         } else {
1180             // We iterate "up" using the following formula:
1181             //
1182             // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1183             //
1184             // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
1185             let mut inverse = table_inverse;
1186             let mut going_mod = INV_TABLE_MOD_SQUARED;
1187             loop {
1188                 // y = y * (2 - xy) mod n
1189                 //
1190                 // Note, that we use wrapping operations here intentionally – the original formula
1191                 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
1192                 // usize::MAX` instead, because we take the result `mod n` at the end
1193                 // anyway.
1194                 inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse)));
1195                 if going_mod >= m {
1196                     return inverse & m_minus_one;
1197                 }
1198                 going_mod = wrapping_mul(going_mod, going_mod);
1199             }
1200         }
1201     }
1202
1203     let stride = mem::size_of::<T>();
1204     // SAFETY: `a` is a power-of-two, therefore non-zero.
1205     let a_minus_one = unsafe { unchecked_sub(a, 1) };
1206     if stride == 1 {
1207         // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so
1208         // inhibits LLVM's ability to select instructions like `lea`. Instead we compute
1209         //
1210         //    round_up_to_next_alignment(p, a) - p
1211         //
1212         // which distributes operations around the load-bearing, but pessimizing `and` sufficiently
1213         // for LLVM to be able to utilize the various optimizations it knows about.
1214         return wrapping_sub(
1215             wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a),
1216             p as usize,
1217         );
1218     }
1219
1220     let pmoda = p as usize & a_minus_one;
1221     if pmoda == 0 {
1222         // Already aligned. Yay!
1223         return 0;
1224     } else if stride == 0 {
1225         // If the pointer is not aligned, and the element is zero-sized, then no amount of
1226         // elements will ever align the pointer.
1227         return usize::MAX;
1228     }
1229
1230     let smoda = stride & a_minus_one;
1231     // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
1232     let gcdpow = unsafe { intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)) };
1233     // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize.
1234     let gcd = unsafe { unchecked_shl(1usize, gcdpow) };
1235
1236     // SAFETY: gcd is always greater or equal to 1.
1237     if p as usize & unsafe { unchecked_sub(gcd, 1) } == 0 {
1238         // This branch solves for the following linear congruence equation:
1239         //
1240         // ` p + so = 0 mod a `
1241         //
1242         // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1243         // requested alignment.
1244         //
1245         // With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
1246         // `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1247         //
1248         // ` p' + s'o = 0 mod a' `
1249         // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1250         //
1251         // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the second
1252         // term is "how does incrementing `p` by `s` bytes change the relative alignment of `p`" (again
1253         // divided by `g`).
1254         // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1255         // co-prime.
1256         //
1257         // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1258         // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`.
1259
1260         // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1261         // `a`.
1262         let a2 = unsafe { unchecked_shr(a, gcdpow) };
1263         // SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
1264         // in `a` (of which it has exactly one).
1265         let a2minus1 = unsafe { unchecked_sub(a2, 1) };
1266         // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1267         // `a`.
1268         let s2 = unsafe { unchecked_shr(smoda, gcdpow) };
1269         // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1270         // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
1271         // always be strictly greater than `(p % a) >> gcdpow`.
1272         let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(pmoda, gcdpow)) };
1273         // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
1274         // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
1275         return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;
1276     }
1277
1278     // Cannot be aligned at all.
1279     usize::MAX
1280 }
1281
1282 /// Compares raw pointers for equality.
1283 ///
1284 /// This is the same as using the `==` operator, but less generic:
1285 /// the arguments have to be `*const T` raw pointers,
1286 /// not anything that implements `PartialEq`.
1287 ///
1288 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
1289 /// by their address rather than comparing the values they point to
1290 /// (which is what the `PartialEq for &T` implementation does).
1291 ///
1292 /// # Examples
1293 ///
1294 /// ```
1295 /// use std::ptr;
1296 ///
1297 /// let five = 5;
1298 /// let other_five = 5;
1299 /// let five_ref = &five;
1300 /// let same_five_ref = &five;
1301 /// let other_five_ref = &other_five;
1302 ///
1303 /// assert!(five_ref == same_five_ref);
1304 /// assert!(ptr::eq(five_ref, same_five_ref));
1305 ///
1306 /// assert!(five_ref == other_five_ref);
1307 /// assert!(!ptr::eq(five_ref, other_five_ref));
1308 /// ```
1309 ///
1310 /// Slices are also compared by their length (fat pointers):
1311 ///
1312 /// ```
1313 /// let a = [1, 2, 3];
1314 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
1315 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
1316 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
1317 /// ```
1318 ///
1319 /// Traits are also compared by their implementation:
1320 ///
1321 /// ```
1322 /// #[repr(transparent)]
1323 /// struct Wrapper { member: i32 }
1324 ///
1325 /// trait Trait {}
1326 /// impl Trait for Wrapper {}
1327 /// impl Trait for i32 {}
1328 ///
1329 /// let wrapper = Wrapper { member: 10 };
1330 ///
1331 /// // Pointers have equal addresses.
1332 /// assert!(std::ptr::eq(
1333 ///     &wrapper as *const Wrapper as *const u8,
1334 ///     &wrapper.member as *const i32 as *const u8
1335 /// ));
1336 ///
1337 /// // Objects have equal addresses, but `Trait` has different implementations.
1338 /// assert!(!std::ptr::eq(
1339 ///     &wrapper as &dyn Trait,
1340 ///     &wrapper.member as &dyn Trait,
1341 /// ));
1342 /// assert!(!std::ptr::eq(
1343 ///     &wrapper as &dyn Trait as *const dyn Trait,
1344 ///     &wrapper.member as &dyn Trait as *const dyn Trait,
1345 /// ));
1346 ///
1347 /// // Converting the reference to a `*const u8` compares by address.
1348 /// assert!(std::ptr::eq(
1349 ///     &wrapper as &dyn Trait as *const dyn Trait as *const u8,
1350 ///     &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
1351 /// ));
1352 /// ```
1353 #[stable(feature = "ptr_eq", since = "1.17.0")]
1354 #[inline]
1355 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
1356     a == b
1357 }
1358
1359 /// Hash a raw pointer.
1360 ///
1361 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
1362 /// by its address rather than the value it points to
1363 /// (which is what the `Hash for &T` implementation does).
1364 ///
1365 /// # Examples
1366 ///
1367 /// ```
1368 /// use std::collections::hash_map::DefaultHasher;
1369 /// use std::hash::{Hash, Hasher};
1370 /// use std::ptr;
1371 ///
1372 /// let five = 5;
1373 /// let five_ref = &five;
1374 ///
1375 /// let mut hasher = DefaultHasher::new();
1376 /// ptr::hash(five_ref, &mut hasher);
1377 /// let actual = hasher.finish();
1378 ///
1379 /// let mut hasher = DefaultHasher::new();
1380 /// (five_ref as *const i32).hash(&mut hasher);
1381 /// let expected = hasher.finish();
1382 ///
1383 /// assert_eq!(actual, expected);
1384 /// ```
1385 #[stable(feature = "ptr_hash", since = "1.35.0")]
1386 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
1387     use crate::hash::Hash;
1388     hashee.hash(into);
1389 }
1390
1391 // Impls for function pointers
1392 macro_rules! fnptr_impls_safety_abi {
1393     ($FnTy: ty, $($Arg: ident),*) => {
1394         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1395         impl<Ret, $($Arg),*> PartialEq for $FnTy {
1396             #[inline]
1397             fn eq(&self, other: &Self) -> bool {
1398                 *self as usize == *other as usize
1399             }
1400         }
1401
1402         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1403         impl<Ret, $($Arg),*> Eq for $FnTy {}
1404
1405         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1406         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
1407             #[inline]
1408             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1409                 (*self as usize).partial_cmp(&(*other as usize))
1410             }
1411         }
1412
1413         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1414         impl<Ret, $($Arg),*> Ord for $FnTy {
1415             #[inline]
1416             fn cmp(&self, other: &Self) -> Ordering {
1417                 (*self as usize).cmp(&(*other as usize))
1418             }
1419         }
1420
1421         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1422         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
1423             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
1424                 state.write_usize(*self as usize)
1425             }
1426         }
1427
1428         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1429         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
1430             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1431                 // HACK: The intermediate cast as usize is required for AVR
1432                 // so that the address space of the source function pointer
1433                 // is preserved in the final function pointer.
1434                 //
1435                 // https://github.com/avr-rust/rust/issues/143
1436                 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1437             }
1438         }
1439
1440         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1441         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
1442             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1443                 // HACK: The intermediate cast as usize is required for AVR
1444                 // so that the address space of the source function pointer
1445                 // is preserved in the final function pointer.
1446                 //
1447                 // https://github.com/avr-rust/rust/issues/143
1448                 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1449             }
1450         }
1451     }
1452 }
1453
1454 macro_rules! fnptr_impls_args {
1455     ($($Arg: ident),+) => {
1456         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1457         fnptr_impls_safety_abi! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1458         fnptr_impls_safety_abi! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1459         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1460         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1461         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1462     };
1463     () => {
1464         // No variadic functions with 0 parameters
1465         fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
1466         fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
1467         fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
1468         fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
1469     };
1470 }
1471
1472 fnptr_impls_args! {}
1473 fnptr_impls_args! { A }
1474 fnptr_impls_args! { A, B }
1475 fnptr_impls_args! { A, B, C }
1476 fnptr_impls_args! { A, B, C, D }
1477 fnptr_impls_args! { A, B, C, D, E }
1478 fnptr_impls_args! { A, B, C, D, E, F }
1479 fnptr_impls_args! { A, B, C, D, E, F, G }
1480 fnptr_impls_args! { A, B, C, D, E, F, G, H }
1481 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
1482 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
1483 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
1484 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
1485
1486 /// Create a `const` raw pointer to a place, without creating an intermediate reference.
1487 ///
1488 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1489 /// and points to initialized data. For cases where those requirements do not hold,
1490 /// raw pointers should be used instead. However, `&expr as *const _` creates a reference
1491 /// before casting it to a raw pointer, and that reference is subject to the same rules
1492 /// as all other references. This macro can create a raw pointer *without* creating
1493 /// a reference first.
1494 ///
1495 /// Note, however, that the `expr` in `addr_of!(expr)` is still subject to all
1496 /// the usual rules. In particular, `addr_of!(*ptr::null())` is Undefined
1497 /// Behavior because it dereferences a null pointer.
1498 ///
1499 /// # Example
1500 ///
1501 /// ```
1502 /// use std::ptr;
1503 ///
1504 /// #[repr(packed)]
1505 /// struct Packed {
1506 ///     f1: u8,
1507 ///     f2: u16,
1508 /// }
1509 ///
1510 /// let packed = Packed { f1: 1, f2: 2 };
1511 /// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1512 /// let raw_f2 = ptr::addr_of!(packed.f2);
1513 /// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
1514 /// ```
1515 ///
1516 /// See [`addr_of_mut`] for how to create a pointer to unininitialized data.
1517 /// Doing that with `addr_of` would not make much sense since one could only
1518 /// read the data, and that would be Undefined Behavior.
1519 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1520 #[rustc_macro_transparency = "semitransparent"]
1521 #[allow_internal_unstable(raw_ref_op)]
1522 pub macro addr_of($place:expr) {
1523     &raw const $place
1524 }
1525
1526 /// Create a `mut` raw pointer to a place, without creating an intermediate reference.
1527 ///
1528 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1529 /// and points to initialized data. For cases where those requirements do not hold,
1530 /// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
1531 /// before casting it to a raw pointer, and that reference is subject to the same rules
1532 /// as all other references. This macro can create a raw pointer *without* creating
1533 /// a reference first.
1534 ///
1535 /// Note, however, that the `expr` in `addr_of_mut!(expr)` is still subject to all
1536 /// the usual rules. In particular, `addr_of_mut!(*ptr::null_mut())` is Undefined
1537 /// Behavior because it dereferences a null pointer.
1538 ///
1539 /// # Examples
1540 ///
1541 /// **Creating a pointer to unaligned data:**
1542 ///
1543 /// ```
1544 /// use std::ptr;
1545 ///
1546 /// #[repr(packed)]
1547 /// struct Packed {
1548 ///     f1: u8,
1549 ///     f2: u16,
1550 /// }
1551 ///
1552 /// let mut packed = Packed { f1: 1, f2: 2 };
1553 /// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1554 /// let raw_f2 = ptr::addr_of_mut!(packed.f2);
1555 /// unsafe { raw_f2.write_unaligned(42); }
1556 /// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
1557 /// ```
1558 ///
1559 /// **Creating a pointer to uninitialized data:**
1560 ///
1561 /// ```rust
1562 /// use std::{ptr, mem::MaybeUninit};
1563 ///
1564 /// struct Demo {
1565 ///     field: bool,
1566 /// }
1567 ///
1568 /// let mut uninit = MaybeUninit::<Demo>::uninit();
1569 /// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
1570 /// // and thus be Undefined Behavior!
1571 /// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
1572 /// unsafe { f1_ptr.write(true); }
1573 /// let init = unsafe { uninit.assume_init() };
1574 /// ```
1575 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1576 #[rustc_macro_transparency = "semitransparent"]
1577 #[allow_internal_unstable(raw_ref_op)]
1578 pub macro addr_of_mut($place:expr) {
1579     &raw mut $place
1580 }