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