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