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