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