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