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