]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
Stabilize pointer::align_offset
[rust.git] / src / libcore / ptr.rs
1 // ignore-tidy-filelength
2
3 //! Manually manage memory through raw pointers.
4 //!
5 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
6 //!
7 //! # Safety
8 //!
9 //! Many functions in this module take raw pointers as arguments and read from
10 //! or write to them. For this to be safe, these pointers must be *valid*.
11 //! Whether a pointer is valid depends on the operation it is used for
12 //! (read or write), and the extent of the memory that is accessed (i.e.,
13 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
14 //! to access only a single value, in which case the documentation omits the size
15 //! and implicitly assumes it to be `size_of::<T>()` bytes.
16 //!
17 //! The precise rules for validity are not determined yet. The guarantees that are
18 //! provided at this point are very minimal:
19 //!
20 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
21 //! * All pointers (except for the null pointer) are valid for all operations of
22 //!   [size zero][zst].
23 //! * All accesses performed by functions in this module are *non-atomic* in the sense
24 //!   of [atomic operations] used to synchronize between threads. This means it is
25 //!   undefined behavior to perform two concurrent accesses to the same location from different
26 //!   threads unless both accesses only read from memory. Notice that this explicitly
27 //!   includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
28 //!   be used for inter-thread synchronization.
29 //! * The result of casting a reference to a pointer is valid for as long as the
30 //!   underlying object is live and no reference (just raw pointers) is used to
31 //!   access the same memory.
32 //!
33 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
34 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
35 //! will be provided eventually, as the [aliasing] rules are being determined. For more
36 //! information, see the [book] as well as the section in the reference devoted
37 //! to [undefined behavior][ub].
38 //!
39 //! ## Alignment
40 //!
41 //! Valid raw pointers as defined above are not necessarily properly aligned (where
42 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
43 //! aligned to `mem::align_of::<T>()`). However, most functions require their
44 //! arguments to be properly aligned, and will explicitly state
45 //! this requirement in their documentation. Notable exceptions to this are
46 //! [`read_unaligned`] and [`write_unaligned`].
47 //!
48 //! When a function requires proper alignment, it does so even if the access
49 //! has size 0, i.e., even if memory is not actually touched. Consider using
50 //! [`NonNull::dangling`] in such cases.
51 //!
52 //! [aliasing]: ../../nomicon/aliasing.html
53 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
54 //! [ub]: ../../reference/behavior-considered-undefined.html
55 //! [null]: ./fn.null.html
56 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
57 //! [atomic operations]: ../../std/sync/atomic/index.html
58 //! [`copy`]: ../../std/ptr/fn.copy.html
59 //! [`offset`]: ../../std/primitive.pointer.html#method.offset
60 //! [`read_unaligned`]: ./fn.read_unaligned.html
61 //! [`write_unaligned`]: ./fn.write_unaligned.html
62 //! [`read_volatile`]: ./fn.read_volatile.html
63 //! [`write_volatile`]: ./fn.write_volatile.html
64 //! [`NonNull::dangling`]: ./struct.NonNull.html#method.dangling
65
66 #![stable(feature = "rust1", since = "1.0.0")]
67
68 use crate::convert::From;
69 use crate::intrinsics;
70 use crate::ops::{CoerceUnsized, DispatchFromDyn};
71 use crate::fmt;
72 use crate::hash;
73 use crate::marker::{PhantomData, Unsize};
74 use crate::mem::{self, MaybeUninit};
75
76 use crate::cmp::Ordering::{self, Less, Equal, Greater};
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 /// Executes the destructor (if any) of the pointed-to value.
88 ///
89 /// This is semantically equivalent to calling [`ptr::read`] and discarding
90 /// the result, but has the following advantages:
91 ///
92 /// * It is *required* to use `drop_in_place` to drop unsized types like
93 ///   trait objects, because they can't be read out onto the stack and
94 ///   dropped normally.
95 ///
96 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
97 ///   dropping manually allocated memory (e.g., when writing Box/Rc/Vec),
98 ///   as the compiler doesn't need to prove that it's sound to elide the
99 ///   copy.
100 ///
101 /// [`ptr::read`]: ../ptr/fn.read.html
102 ///
103 /// # Safety
104 ///
105 /// Behavior is undefined if any of the following conditions are violated:
106 ///
107 /// * `to_drop` must be [valid] for reads.
108 ///
109 /// * `to_drop` must be properly aligned. See the example below for how to drop
110 ///   an unaligned pointer.
111 ///
112 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
113 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
114 /// foo` counts as a use because it will cause the value to be dropped
115 /// again. [`write`] can be used to overwrite data without causing it to be
116 /// dropped.
117 ///
118 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
119 ///
120 /// [valid]: ../ptr/index.html#safety
121 /// [`Copy`]: ../marker/trait.Copy.html
122 /// [`write`]: ../ptr/fn.write.html
123 ///
124 /// # Examples
125 ///
126 /// Manually remove the last item from a vector:
127 ///
128 /// ```
129 /// use std::ptr;
130 /// use std::rc::Rc;
131 ///
132 /// let last = Rc::new(1);
133 /// let weak = Rc::downgrade(&last);
134 ///
135 /// let mut v = vec![Rc::new(0), last];
136 ///
137 /// unsafe {
138 ///     // Get a raw pointer to the last element in `v`.
139 ///     let ptr = &mut v[1] as *mut _;
140 ///     // Shorten `v` to prevent the last item from being dropped. We do that first,
141 ///     // to prevent issues if the `drop_in_place` below panics.
142 ///     v.set_len(1);
143 ///     // Without a call `drop_in_place`, the last item would never be dropped,
144 ///     // and the memory it manages would be leaked.
145 ///     ptr::drop_in_place(ptr);
146 /// }
147 ///
148 /// assert_eq!(v, &[0.into()]);
149 ///
150 /// // Ensure that the last item was dropped.
151 /// assert!(weak.upgrade().is_none());
152 /// ```
153 ///
154 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
155 /// location first:
156 /// ```
157 /// use std::ptr;
158 /// use std::mem;
159 ///
160 /// unsafe fn drop_after_copy<T>(to_drop: *mut T) {
161 ///     let mut copy: T = mem::uninitialized();
162 ///     ptr::copy(to_drop, &mut copy, 1);
163 ///     drop(copy);
164 /// }
165 ///
166 /// #[repr(packed, C)]
167 /// struct Packed {
168 ///     _padding: u8,
169 ///     unaligned: Vec<i32>,
170 /// }
171 ///
172 /// let mut p = Packed { _padding: 0, unaligned: vec![42] };
173 /// unsafe {
174 ///     drop_after_copy(&mut p.unaligned as *mut _);
175 ///     mem::forget(p);
176 /// }
177 /// ```
178 ///
179 /// Notice that the compiler performs this copy automatically when dropping packed structs,
180 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
181 /// manually.
182 #[stable(feature = "drop_in_place", since = "1.8.0")]
183 #[inline(always)]
184 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
185     real_drop_in_place(&mut *to_drop)
186 }
187
188 // The real `drop_in_place` -- the one that gets called implicitly when variables go
189 // out of scope -- should have a safe reference and not a raw pointer as argument
190 // type.  When we drop a local variable, we access it with a pointer that behaves
191 // like a safe reference; transmuting that to a raw pointer does not mean we can
192 // actually access it with raw pointers.
193 #[lang = "drop_in_place"]
194 #[allow(unconditional_recursion)]
195 unsafe fn real_drop_in_place<T: ?Sized>(to_drop: &mut T) {
196     // Code here does not matter - this is replaced by the
197     // real drop glue by the compiler.
198     real_drop_in_place(to_drop)
199 }
200
201 /// Creates a null raw pointer.
202 ///
203 /// # Examples
204 ///
205 /// ```
206 /// use std::ptr;
207 ///
208 /// let p: *const i32 = ptr::null();
209 /// assert!(p.is_null());
210 /// ```
211 #[inline]
212 #[stable(feature = "rust1", since = "1.0.0")]
213 #[rustc_promotable]
214 pub const fn null<T>() -> *const T { 0 as *const T }
215
216 /// Creates a null mutable raw pointer.
217 ///
218 /// # Examples
219 ///
220 /// ```
221 /// use std::ptr;
222 ///
223 /// let p: *mut i32 = ptr::null_mut();
224 /// assert!(p.is_null());
225 /// ```
226 #[inline]
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[rustc_promotable]
229 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
230
231 /// Swaps the values at two mutable locations of the same type, without
232 /// deinitializing either.
233 ///
234 /// But for the following two exceptions, this function is semantically
235 /// equivalent to [`mem::swap`]:
236 ///
237 /// * It operates on raw pointers instead of references. When references are
238 ///   available, [`mem::swap`] should be preferred.
239 ///
240 /// * The two pointed-to values may overlap. If the values do overlap, then the
241 ///   overlapping region of memory from `x` will be used. This is demonstrated
242 ///   in the second example below.
243 ///
244 /// [`mem::swap`]: ../mem/fn.swap.html
245 ///
246 /// # Safety
247 ///
248 /// Behavior is undefined if any of the following conditions are violated:
249 ///
250 /// * Both `x` and `y` must be [valid] for reads and writes.
251 ///
252 /// * Both `x` and `y` must be properly aligned.
253 ///
254 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
255 ///
256 /// [valid]: ../ptr/index.html#safety
257 ///
258 /// # Examples
259 ///
260 /// Swapping two non-overlapping regions:
261 ///
262 /// ```
263 /// use std::ptr;
264 ///
265 /// let mut array = [0, 1, 2, 3];
266 ///
267 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
268 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
269 ///
270 /// unsafe {
271 ///     ptr::swap(x, y);
272 ///     assert_eq!([2, 3, 0, 1], array);
273 /// }
274 /// ```
275 ///
276 /// Swapping two overlapping regions:
277 ///
278 /// ```
279 /// use std::ptr;
280 ///
281 /// let mut array = [0, 1, 2, 3];
282 ///
283 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
284 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
285 ///
286 /// unsafe {
287 ///     ptr::swap(x, y);
288 ///     // The indices `1..3` of the slice overlap between `x` and `y`.
289 ///     // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
290 ///     // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
291 ///     // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
292 ///     // This implementation is defined to make the latter choice.
293 ///     assert_eq!([1, 0, 1, 2], array);
294 /// }
295 /// ```
296 #[inline]
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
299     // Give ourselves some scratch space to work with.
300     // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
301     let mut tmp = MaybeUninit::<T>::uninit();
302
303     // Perform the swap
304     copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
305     copy(y, x, 1); // `x` and `y` may overlap
306     copy_nonoverlapping(tmp.as_ptr(), y, 1);
307 }
308
309 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
310 /// beginning at `x` and `y`. The two regions must *not* overlap.
311 ///
312 /// # Safety
313 ///
314 /// Behavior is undefined if any of the following conditions are violated:
315 ///
316 /// * Both `x` and `y` must be [valid] for reads and writes of `count *
317 ///   size_of::<T>()` bytes.
318 ///
319 /// * Both `x` and `y` must be properly aligned.
320 ///
321 /// * The region of memory beginning at `x` with a size of `count *
322 ///   size_of::<T>()` bytes must *not* overlap with the region of memory
323 ///   beginning at `y` with the same size.
324 ///
325 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
326 /// the pointers must be non-NULL and properly aligned.
327 ///
328 /// [valid]: ../ptr/index.html#safety
329 ///
330 /// # Examples
331 ///
332 /// Basic usage:
333 ///
334 /// ```
335 /// use std::ptr;
336 ///
337 /// let mut x = [1, 2, 3, 4];
338 /// let mut y = [7, 8, 9];
339 ///
340 /// unsafe {
341 ///     ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
342 /// }
343 ///
344 /// assert_eq!(x, [7, 8, 3, 4]);
345 /// assert_eq!(y, [1, 2, 9]);
346 /// ```
347 #[inline]
348 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
349 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
350     let x = x as *mut u8;
351     let y = y as *mut u8;
352     let len = mem::size_of::<T>() * count;
353     swap_nonoverlapping_bytes(x, y, len)
354 }
355
356 #[inline]
357 pub(crate) unsafe fn swap_nonoverlapping_one<T>(x: *mut T, y: *mut T) {
358     // For types smaller than the block optimization below,
359     // just swap directly to avoid pessimizing codegen.
360     if mem::size_of::<T>() < 32 {
361         let z = read(x);
362         copy_nonoverlapping(y, x, 1);
363         write(y, z);
364     } else {
365         swap_nonoverlapping(x, y, 1);
366     }
367 }
368
369 #[inline]
370 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
371     // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
372     // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
373     // Haswell E processors. LLVM is more able to optimize if we give a struct a
374     // #[repr(simd)], even if we don't actually use this struct directly.
375     //
376     // FIXME repr(simd) broken on emscripten and redox
377     // It's also broken on big-endian powerpc64 and s390x.  #42778
378     #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox",
379                        target_endian = "big")),
380                repr(simd))]
381     struct Block(u64, u64, u64, u64);
382     struct UnalignedBlock(u64, u64, u64, u64);
383
384     let block_size = mem::size_of::<Block>();
385
386     // Loop through x & y, copying them `Block` at a time
387     // The optimizer should unroll the loop fully for most types
388     // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
389     let mut i = 0;
390     while i + block_size <= len {
391         // Create some uninitialized memory as scratch space
392         // Declaring `t` here avoids aligning the stack when this loop is unused
393         let mut t = mem::MaybeUninit::<Block>::uninit();
394         let t = t.as_mut_ptr() as *mut u8;
395         let x = x.add(i);
396         let y = y.add(i);
397
398         // Swap a block of bytes of x & y, using t as a temporary buffer
399         // This should be optimized into efficient SIMD operations where available
400         copy_nonoverlapping(x, t, block_size);
401         copy_nonoverlapping(y, x, block_size);
402         copy_nonoverlapping(t, y, block_size);
403         i += block_size;
404     }
405
406     if i < len {
407         // Swap any remaining bytes
408         let mut t = mem::MaybeUninit::<UnalignedBlock>::uninit();
409         let rem = len - i;
410
411         let t = t.as_mut_ptr() as *mut u8;
412         let x = x.add(i);
413         let y = y.add(i);
414
415         copy_nonoverlapping(x, t, rem);
416         copy_nonoverlapping(y, x, rem);
417         copy_nonoverlapping(t, y, rem);
418     }
419 }
420
421 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
422 ///
423 /// Neither value is dropped.
424 ///
425 /// This function is semantically equivalent to [`mem::replace`] except that it
426 /// operates on raw pointers instead of references. When references are
427 /// available, [`mem::replace`] should be preferred.
428 ///
429 /// [`mem::replace`]: ../mem/fn.replace.html
430 ///
431 /// # Safety
432 ///
433 /// Behavior is undefined if any of the following conditions are violated:
434 ///
435 /// * `dst` must be [valid] for writes.
436 ///
437 /// * `dst` must be properly aligned.
438 ///
439 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
440 ///
441 /// [valid]: ../ptr/index.html#safety
442 ///
443 /// # Examples
444 ///
445 /// ```
446 /// use std::ptr;
447 ///
448 /// let mut rust = vec!['b', 'u', 's', 't'];
449 ///
450 /// // `mem::replace` would have the same effect without requiring the unsafe
451 /// // block.
452 /// let b = unsafe {
453 ///     ptr::replace(&mut rust[0], 'r')
454 /// };
455 ///
456 /// assert_eq!(b, 'b');
457 /// assert_eq!(rust, &['r', 'u', 's', 't']);
458 /// ```
459 #[inline]
460 #[stable(feature = "rust1", since = "1.0.0")]
461 pub unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
462     mem::swap(&mut *dst, &mut src); // cannot overlap
463     src
464 }
465
466 /// Reads the value from `src` without moving it. This leaves the
467 /// memory in `src` unchanged.
468 ///
469 /// # Safety
470 ///
471 /// Behavior is undefined if any of the following conditions are violated:
472 ///
473 /// * `src` must be [valid] for reads.
474 ///
475 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
476 ///   case.
477 ///
478 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
479 ///
480 /// # Examples
481 ///
482 /// Basic usage:
483 ///
484 /// ```
485 /// let x = 12;
486 /// let y = &x as *const i32;
487 ///
488 /// unsafe {
489 ///     assert_eq!(std::ptr::read(y), 12);
490 /// }
491 /// ```
492 ///
493 /// Manually implement [`mem::swap`]:
494 ///
495 /// ```
496 /// use std::ptr;
497 ///
498 /// fn swap<T>(a: &mut T, b: &mut T) {
499 ///     unsafe {
500 ///         // Create a bitwise copy of the value at `a` in `tmp`.
501 ///         let tmp = ptr::read(a);
502 ///
503 ///         // Exiting at this point (either by explicitly returning or by
504 ///         // calling a function which panics) would cause the value in `tmp` to
505 ///         // be dropped while the same value is still referenced by `a`. This
506 ///         // could trigger undefined behavior if `T` is not `Copy`.
507 ///
508 ///         // Create a bitwise copy of the value at `b` in `a`.
509 ///         // This is safe because mutable references cannot alias.
510 ///         ptr::copy_nonoverlapping(b, a, 1);
511 ///
512 ///         // As above, exiting here could trigger undefined behavior because
513 ///         // the same value is referenced by `a` and `b`.
514 ///
515 ///         // Move `tmp` into `b`.
516 ///         ptr::write(b, tmp);
517 ///
518 ///         // `tmp` has been moved (`write` takes ownership of its second argument),
519 ///         // so nothing is dropped implicitly here.
520 ///     }
521 /// }
522 ///
523 /// let mut foo = "foo".to_owned();
524 /// let mut bar = "bar".to_owned();
525 ///
526 /// swap(&mut foo, &mut bar);
527 ///
528 /// assert_eq!(foo, "bar");
529 /// assert_eq!(bar, "foo");
530 /// ```
531 ///
532 /// ## Ownership of the Returned Value
533 ///
534 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
535 /// If `T` is not [`Copy`], using both the returned value and the value at
536 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
537 /// use because it will attempt to drop the value at `*src`.
538 ///
539 /// [`write`] can be used to overwrite data without causing it to be dropped.
540 ///
541 /// ```
542 /// use std::ptr;
543 ///
544 /// let mut s = String::from("foo");
545 /// unsafe {
546 ///     // `s2` now points to the same underlying memory as `s`.
547 ///     let mut s2: String = ptr::read(&s);
548 ///
549 ///     assert_eq!(s2, "foo");
550 ///
551 ///     // Assigning to `s2` causes its original value to be dropped. Beyond
552 ///     // this point, `s` must no longer be used, as the underlying memory has
553 ///     // been freed.
554 ///     s2 = String::default();
555 ///     assert_eq!(s2, "");
556 ///
557 ///     // Assigning to `s` would cause the old value to be dropped again,
558 ///     // resulting in undefined behavior.
559 ///     // s = String::from("bar"); // ERROR
560 ///
561 ///     // `ptr::write` can be used to overwrite a value without dropping it.
562 ///     ptr::write(&mut s, String::from("bar"));
563 /// }
564 ///
565 /// assert_eq!(s, "bar");
566 /// ```
567 ///
568 /// [`mem::swap`]: ../mem/fn.swap.html
569 /// [valid]: ../ptr/index.html#safety
570 /// [`Copy`]: ../marker/trait.Copy.html
571 /// [`read_unaligned`]: ./fn.read_unaligned.html
572 /// [`write`]: ./fn.write.html
573 #[inline]
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub unsafe fn read<T>(src: *const T) -> T {
576     let mut tmp = MaybeUninit::<T>::uninit();
577     copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
578     tmp.assume_init()
579 }
580
581 /// Reads the value from `src` without moving it. This leaves the
582 /// memory in `src` unchanged.
583 ///
584 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
585 ///
586 /// # Safety
587 ///
588 /// Behavior is undefined if any of the following conditions are violated:
589 ///
590 /// * `src` must be [valid] for reads.
591 ///
592 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
593 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
594 /// value and the value at `*src` can [violate memory safety][read-ownership].
595 ///
596 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
597 ///
598 /// [`Copy`]: ../marker/trait.Copy.html
599 /// [`read`]: ./fn.read.html
600 /// [`write_unaligned`]: ./fn.write_unaligned.html
601 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
602 /// [valid]: ../ptr/index.html#safety
603 ///
604 /// # Examples
605 ///
606 /// Access members of a packed struct by reference:
607 ///
608 /// ```
609 /// use std::ptr;
610 ///
611 /// #[repr(packed, C)]
612 /// struct Packed {
613 ///     _padding: u8,
614 ///     unaligned: u32,
615 /// }
616 ///
617 /// let x = Packed {
618 ///     _padding: 0x00,
619 ///     unaligned: 0x01020304,
620 /// };
621 ///
622 /// let v = unsafe {
623 ///     // Take the address of a 32-bit integer which is not aligned.
624 ///     // This must be done as a raw pointer; unaligned references are invalid.
625 ///     let unaligned = &x.unaligned as *const u32;
626 ///
627 ///     // Dereferencing normally will emit an aligned load instruction,
628 ///     // causing undefined behavior.
629 ///     // let v = *unaligned; // ERROR
630 ///
631 ///     // Instead, use `read_unaligned` to read improperly aligned values.
632 ///     let v = ptr::read_unaligned(unaligned);
633 ///
634 ///     v
635 /// };
636 ///
637 /// // Accessing unaligned values directly is safe.
638 /// assert!(x.unaligned == v);
639 /// ```
640 #[inline]
641 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
642 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
643     let mut tmp = MaybeUninit::<T>::uninit();
644     copy_nonoverlapping(src as *const u8,
645                         tmp.as_mut_ptr() as *mut u8,
646                         mem::size_of::<T>());
647     tmp.assume_init()
648 }
649
650 /// Overwrites a memory location with the given value without reading or
651 /// dropping the old value.
652 ///
653 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
654 /// allocations or resources, so care should be taken not to overwrite an object
655 /// that should be dropped.
656 ///
657 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
658 /// location pointed to by `dst`.
659 ///
660 /// This is appropriate for initializing uninitialized memory, or overwriting
661 /// memory that has previously been [`read`] from.
662 ///
663 /// [`read`]: ./fn.read.html
664 ///
665 /// # Safety
666 ///
667 /// Behavior is undefined if any of the following conditions are violated:
668 ///
669 /// * `dst` must be [valid] for writes.
670 ///
671 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
672 ///   case.
673 ///
674 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
675 ///
676 /// [valid]: ../ptr/index.html#safety
677 /// [`write_unaligned`]: ./fn.write_unaligned.html
678 ///
679 /// # Examples
680 ///
681 /// Basic usage:
682 ///
683 /// ```
684 /// let mut x = 0;
685 /// let y = &mut x as *mut i32;
686 /// let z = 12;
687 ///
688 /// unsafe {
689 ///     std::ptr::write(y, z);
690 ///     assert_eq!(std::ptr::read(y), 12);
691 /// }
692 /// ```
693 ///
694 /// Manually implement [`mem::swap`]:
695 ///
696 /// ```
697 /// use std::ptr;
698 ///
699 /// fn swap<T>(a: &mut T, b: &mut T) {
700 ///     unsafe {
701 ///         // Create a bitwise copy of the value at `a` in `tmp`.
702 ///         let tmp = ptr::read(a);
703 ///
704 ///         // Exiting at this point (either by explicitly returning or by
705 ///         // calling a function which panics) would cause the value in `tmp` to
706 ///         // be dropped while the same value is still referenced by `a`. This
707 ///         // could trigger undefined behavior if `T` is not `Copy`.
708 ///
709 ///         // Create a bitwise copy of the value at `b` in `a`.
710 ///         // This is safe because mutable references cannot alias.
711 ///         ptr::copy_nonoverlapping(b, a, 1);
712 ///
713 ///         // As above, exiting here could trigger undefined behavior because
714 ///         // the same value is referenced by `a` and `b`.
715 ///
716 ///         // Move `tmp` into `b`.
717 ///         ptr::write(b, tmp);
718 ///
719 ///         // `tmp` has been moved (`write` takes ownership of its second argument),
720 ///         // so nothing is dropped implicitly here.
721 ///     }
722 /// }
723 ///
724 /// let mut foo = "foo".to_owned();
725 /// let mut bar = "bar".to_owned();
726 ///
727 /// swap(&mut foo, &mut bar);
728 ///
729 /// assert_eq!(foo, "bar");
730 /// assert_eq!(bar, "foo");
731 /// ```
732 ///
733 /// [`mem::swap`]: ../mem/fn.swap.html
734 #[inline]
735 #[stable(feature = "rust1", since = "1.0.0")]
736 pub unsafe fn write<T>(dst: *mut T, src: T) {
737     intrinsics::move_val_init(&mut *dst, src)
738 }
739
740 /// Overwrites a memory location with the given value without reading or
741 /// dropping the old value.
742 ///
743 /// Unlike [`write`], the pointer may be unaligned.
744 ///
745 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
746 /// could leak allocations or resources, so care should be taken not to overwrite
747 /// an object that should be dropped.
748 ///
749 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
750 /// location pointed to by `dst`.
751 ///
752 /// This is appropriate for initializing uninitialized memory, or overwriting
753 /// memory that has previously been read with [`read_unaligned`].
754 ///
755 /// [`write`]: ./fn.write.html
756 /// [`read_unaligned`]: ./fn.read_unaligned.html
757 ///
758 /// # Safety
759 ///
760 /// Behavior is undefined if any of the following conditions are violated:
761 ///
762 /// * `dst` must be [valid] for writes.
763 ///
764 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
765 ///
766 /// [valid]: ../ptr/index.html#safety
767 ///
768 /// # Examples
769 ///
770 /// Access fields in a packed struct:
771 ///
772 /// ```
773 /// use std::{mem, ptr};
774 ///
775 /// #[repr(packed, C)]
776 /// #[derive(Default)]
777 /// struct Packed {
778 ///     _padding: u8,
779 ///     unaligned: u32,
780 /// }
781 ///
782 /// let v = 0x01020304;
783 /// let mut x: Packed = unsafe { mem::zeroed() };
784 ///
785 /// unsafe {
786 ///     // Take a reference to a 32-bit integer which is not aligned.
787 ///     let unaligned = &mut x.unaligned as *mut u32;
788 ///
789 ///     // Dereferencing normally will emit an aligned store instruction,
790 ///     // causing undefined behavior because the pointer is not aligned.
791 ///     // *unaligned = v; // ERROR
792 ///
793 ///     // Instead, use `write_unaligned` to write improperly aligned values.
794 ///     ptr::write_unaligned(unaligned, v);
795 /// }
796 ///
797 /// // Accessing unaligned values directly is safe.
798 /// assert!(x.unaligned == v);
799 /// ```
800 #[inline]
801 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
802 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
803     copy_nonoverlapping(&src as *const T as *const u8,
804                         dst as *mut u8,
805                         mem::size_of::<T>());
806     mem::forget(src);
807 }
808
809 /// Performs a volatile read of the value from `src` without moving it. This
810 /// leaves the memory in `src` unchanged.
811 ///
812 /// Volatile operations are intended to act on I/O memory, and are guaranteed
813 /// to not be elided or reordered by the compiler across other volatile
814 /// operations.
815 ///
816 /// Memory accessed with `read_volatile` or [`write_volatile`] should not be
817 /// accessed with non-volatile operations.
818 ///
819 /// [`write_volatile`]: ./fn.write_volatile.html
820 ///
821 /// # Notes
822 ///
823 /// Rust does not currently have a rigorously and formally defined memory model,
824 /// so the precise semantics of what "volatile" means here is subject to change
825 /// over time. That being said, the semantics will almost always end up pretty
826 /// similar to [C11's definition of volatile][c11].
827 ///
828 /// The compiler shouldn't change the relative order or number of volatile
829 /// memory operations. However, volatile memory operations on zero-sized types
830 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
831 /// and may be ignored.
832 ///
833 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
834 ///
835 /// # Safety
836 ///
837 /// Behavior is undefined if any of the following conditions are violated:
838 ///
839 /// * `src` must be [valid] for reads.
840 ///
841 /// * `src` must be properly aligned.
842 ///
843 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
844 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
845 /// value and the value at `*src` can [violate memory safety][read-ownership].
846 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
847 /// incorrect.
848 ///
849 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
850 ///
851 /// [valid]: ../ptr/index.html#safety
852 /// [`Copy`]: ../marker/trait.Copy.html
853 /// [`read`]: ./fn.read.html
854 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
855 ///
856 /// Just like in C, whether an operation is volatile has no bearing whatsoever
857 /// on questions involving concurrent access from multiple threads. Volatile
858 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
859 /// a race between a `read_volatile` and any write operation to the same location
860 /// is undefined behavior.
861 ///
862 /// # Examples
863 ///
864 /// Basic usage:
865 ///
866 /// ```
867 /// let x = 12;
868 /// let y = &x as *const i32;
869 ///
870 /// unsafe {
871 ///     assert_eq!(std::ptr::read_volatile(y), 12);
872 /// }
873 /// ```
874 #[inline]
875 #[stable(feature = "volatile", since = "1.9.0")]
876 pub unsafe fn read_volatile<T>(src: *const T) -> T {
877     intrinsics::volatile_load(src)
878 }
879
880 /// Performs a volatile write of a memory location with the given value without
881 /// reading or dropping the old value.
882 ///
883 /// Volatile operations are intended to act on I/O memory, and are guaranteed
884 /// to not be elided or reordered by the compiler across other volatile
885 /// operations.
886 ///
887 /// Memory accessed with [`read_volatile`] or `write_volatile` should not be
888 /// accessed with non-volatile operations.
889 ///
890 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
891 /// could leak allocations or resources, so care should be taken not to overwrite
892 /// an object that should be dropped.
893 ///
894 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
895 /// location pointed to by `dst`.
896 ///
897 /// [`read_volatile`]: ./fn.read_volatile.html
898 ///
899 /// # Notes
900 ///
901 /// Rust does not currently have a rigorously and formally defined memory model,
902 /// so the precise semantics of what "volatile" means here is subject to change
903 /// over time. That being said, the semantics will almost always end up pretty
904 /// similar to [C11's definition of volatile][c11].
905 ///
906 /// The compiler shouldn't change the relative order or number of volatile
907 /// memory operations. However, volatile memory operations on zero-sized types
908 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
909 /// and may be ignored.
910 ///
911 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
912 ///
913 /// # Safety
914 ///
915 /// Behavior is undefined if any of the following conditions are violated:
916 ///
917 /// * `dst` must be [valid] for writes.
918 ///
919 /// * `dst` must be properly aligned.
920 ///
921 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
922 ///
923 /// [valid]: ../ptr/index.html#safety
924 ///
925 /// Just like in C, whether an operation is volatile has no bearing whatsoever
926 /// on questions involving concurrent access from multiple threads. Volatile
927 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
928 /// a race between a `write_volatile` and any other operation (reading or writing)
929 /// on the same location is undefined behavior.
930 ///
931 /// # Examples
932 ///
933 /// Basic usage:
934 ///
935 /// ```
936 /// let mut x = 0;
937 /// let y = &mut x as *mut i32;
938 /// let z = 12;
939 ///
940 /// unsafe {
941 ///     std::ptr::write_volatile(y, z);
942 ///     assert_eq!(std::ptr::read_volatile(y), 12);
943 /// }
944 /// ```
945 #[inline]
946 #[stable(feature = "volatile", since = "1.9.0")]
947 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
948     intrinsics::volatile_store(dst, src);
949 }
950
951 #[lang = "const_ptr"]
952 impl<T: ?Sized> *const T {
953     /// Returns `true` if the pointer is null.
954     ///
955     /// Note that unsized types have many possible null pointers, as only the
956     /// raw data pointer is considered, not their length, vtable, etc.
957     /// Therefore, two pointers that are null may still not compare equal to
958     /// each other.
959     ///
960     /// # Examples
961     ///
962     /// Basic usage:
963     ///
964     /// ```
965     /// let s: &str = "Follow the rabbit";
966     /// let ptr: *const u8 = s.as_ptr();
967     /// assert!(!ptr.is_null());
968     /// ```
969     #[stable(feature = "rust1", since = "1.0.0")]
970     #[inline]
971     pub fn is_null(self) -> bool {
972         // Compare via a cast to a thin pointer, so fat pointers are only
973         // considering their "data" part for null-ness.
974         (self as *const u8) == null()
975     }
976
977     /// Returns `None` if the pointer is null, or else returns a reference to
978     /// the value wrapped in `Some`.
979     ///
980     /// # Safety
981     ///
982     /// While this method and its mutable counterpart are useful for
983     /// null-safety, it is important to note that this is still an unsafe
984     /// operation because the returned value could be pointing to invalid
985     /// memory.
986     ///
987     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
988     /// not necessarily reflect the actual lifetime of the data.
989     ///
990     /// # Examples
991     ///
992     /// Basic usage:
993     ///
994     /// ```
995     /// let ptr: *const u8 = &10u8 as *const u8;
996     ///
997     /// unsafe {
998     ///     if let Some(val_back) = ptr.as_ref() {
999     ///         println!("We got back the value: {}!", val_back);
1000     ///     }
1001     /// }
1002     /// ```
1003     ///
1004     /// # Null-unchecked version
1005     ///
1006     /// If you are sure the pointer can never be null and are looking for some kind of
1007     /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1008     /// dereference the pointer directly.
1009     ///
1010     /// ```
1011     /// let ptr: *const u8 = &10u8 as *const u8;
1012     ///
1013     /// unsafe {
1014     ///     let val_back = &*ptr;
1015     ///     println!("We got back the value: {}!", val_back);
1016     /// }
1017     /// ```
1018     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1019     #[inline]
1020     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1021         if self.is_null() {
1022             None
1023         } else {
1024             Some(&*self)
1025         }
1026     }
1027
1028     /// Calculates the offset from a pointer.
1029     ///
1030     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1031     /// offset of `3 * size_of::<T>()` bytes.
1032     ///
1033     /// # Safety
1034     ///
1035     /// If any of the following conditions are violated, the result is Undefined
1036     /// Behavior:
1037     ///
1038     /// * Both the starting and resulting pointer must be either in bounds or one
1039     ///   byte past the end of the same allocated object.
1040     ///
1041     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1042     ///
1043     /// * The offset being in bounds cannot rely on "wrapping around" the address
1044     ///   space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1045     ///
1046     /// The compiler and standard library generally tries to ensure allocations
1047     /// never reach a size where an offset is a concern. For instance, `Vec`
1048     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1049     /// `vec.as_ptr().add(vec.len())` is always safe.
1050     ///
1051     /// Most platforms fundamentally can't even construct such an allocation.
1052     /// For instance, no known 64-bit platform can ever serve a request
1053     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1054     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1055     /// more than `isize::MAX` bytes with things like Physical Address
1056     /// Extension. As such, memory acquired directly from allocators or memory
1057     /// mapped files *may* be too large to handle with this function.
1058     ///
1059     /// Consider using `wrapping_offset` instead if these constraints are
1060     /// difficult to satisfy. The only advantage of this method is that it
1061     /// enables more aggressive compiler optimizations.
1062     ///
1063     /// # Examples
1064     ///
1065     /// Basic usage:
1066     ///
1067     /// ```
1068     /// let s: &str = "123";
1069     /// let ptr: *const u8 = s.as_ptr();
1070     ///
1071     /// unsafe {
1072     ///     println!("{}", *ptr.offset(1) as char);
1073     ///     println!("{}", *ptr.offset(2) as char);
1074     /// }
1075     /// ```
1076     #[stable(feature = "rust1", since = "1.0.0")]
1077     #[inline]
1078     pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
1079         intrinsics::offset(self, count)
1080     }
1081
1082     /// Calculates the offset from a pointer using wrapping arithmetic.
1083     ///
1084     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1085     /// offset of `3 * size_of::<T>()` bytes.
1086     ///
1087     /// # Safety
1088     ///
1089     /// The resulting pointer does not need to be in bounds, but it is
1090     /// potentially hazardous to dereference (which requires `unsafe`).
1091     /// In particular, the resulting pointer may *not* be used to access a
1092     /// different allocated object than the one `self` points to. In other
1093     /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1094     /// *not* the same as `y`, and dereferencing it is undefined behavior
1095     /// unless `x` and `y` point into the same allocated object.
1096     ///
1097     /// Always use `.offset(count)` instead when possible, because `offset`
1098     /// allows the compiler to optimize better. If you need to cross object
1099     /// boundaries, cast the pointer to an integer and do the arithmetic there.
1100     ///
1101     /// # Examples
1102     ///
1103     /// Basic usage:
1104     ///
1105     /// ```
1106     /// // Iterate using a raw pointer in increments of two elements
1107     /// let data = [1u8, 2, 3, 4, 5];
1108     /// let mut ptr: *const u8 = data.as_ptr();
1109     /// let step = 2;
1110     /// let end_rounded_up = ptr.wrapping_offset(6);
1111     ///
1112     /// // This loop prints "1, 3, 5, "
1113     /// while ptr != end_rounded_up {
1114     ///     unsafe {
1115     ///         print!("{}, ", *ptr);
1116     ///     }
1117     ///     ptr = ptr.wrapping_offset(step);
1118     /// }
1119     /// ```
1120     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1121     #[inline]
1122     pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
1123         unsafe {
1124             intrinsics::arith_offset(self, count)
1125         }
1126     }
1127
1128     /// Calculates the distance between two pointers. The returned value is in
1129     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1130     ///
1131     /// This function is the inverse of [`offset`].
1132     ///
1133     /// [`offset`]: #method.offset
1134     /// [`wrapping_offset_from`]: #method.wrapping_offset_from
1135     ///
1136     /// # Safety
1137     ///
1138     /// If any of the following conditions are violated, the result is Undefined
1139     /// Behavior:
1140     ///
1141     /// * Both the starting and other pointer must be either in bounds or one
1142     ///   byte past the end of the same allocated object.
1143     ///
1144     /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1145     ///
1146     /// * The distance between the pointers, in bytes, must be an exact multiple
1147     ///   of the size of `T`.
1148     ///
1149     /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1150     ///
1151     /// The compiler and standard library generally try to ensure allocations
1152     /// never reach a size where an offset is a concern. For instance, `Vec`
1153     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1154     /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1155     ///
1156     /// Most platforms fundamentally can't even construct such an allocation.
1157     /// For instance, no known 64-bit platform can ever serve a request
1158     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1159     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1160     /// more than `isize::MAX` bytes with things like Physical Address
1161     /// Extension. As such, memory acquired directly from allocators or memory
1162     /// mapped files *may* be too large to handle with this function.
1163     ///
1164     /// Consider using [`wrapping_offset_from`] instead if these constraints are
1165     /// difficult to satisfy. The only advantage of this method is that it
1166     /// enables more aggressive compiler optimizations.
1167     ///
1168     /// # Panics
1169     ///
1170     /// This function panics if `T` is a Zero-Sized Type ("ZST").
1171     ///
1172     /// # Examples
1173     ///
1174     /// Basic usage:
1175     ///
1176     /// ```
1177     /// #![feature(ptr_offset_from)]
1178     ///
1179     /// let a = [0; 5];
1180     /// let ptr1: *const i32 = &a[1];
1181     /// let ptr2: *const i32 = &a[3];
1182     /// unsafe {
1183     ///     assert_eq!(ptr2.offset_from(ptr1), 2);
1184     ///     assert_eq!(ptr1.offset_from(ptr2), -2);
1185     ///     assert_eq!(ptr1.offset(2), ptr2);
1186     ///     assert_eq!(ptr2.offset(-2), ptr1);
1187     /// }
1188     /// ```
1189     #[unstable(feature = "ptr_offset_from", issue = "41079")]
1190     #[inline]
1191     pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1192         let pointee_size = mem::size_of::<T>();
1193         assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1194
1195         // This is the same sequence that Clang emits for pointer subtraction.
1196         // It can be neither `nsw` nor `nuw` because the input is treated as
1197         // unsigned but then the output is treated as signed, so neither works.
1198         let d = isize::wrapping_sub(self as _, origin as _);
1199         intrinsics::exact_div(d, pointee_size as _)
1200     }
1201
1202     /// Calculates the distance between two pointers. The returned value is in
1203     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1204     ///
1205     /// If the address different between the two pointers is not a multiple of
1206     /// `mem::size_of::<T>()` then the result of the division is rounded towards
1207     /// zero.
1208     ///
1209     /// Though this method is safe for any two pointers, note that its result
1210     /// will be mostly useless if the two pointers aren't into the same allocated
1211     /// object, for example if they point to two different local variables.
1212     ///
1213     /// # Panics
1214     ///
1215     /// This function panics if `T` is a zero-sized type.
1216     ///
1217     /// # Examples
1218     ///
1219     /// Basic usage:
1220     ///
1221     /// ```
1222     /// #![feature(ptr_wrapping_offset_from)]
1223     ///
1224     /// let a = [0; 5];
1225     /// let ptr1: *const i32 = &a[1];
1226     /// let ptr2: *const i32 = &a[3];
1227     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1228     /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1229     /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1230     /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1231     ///
1232     /// let ptr1: *const i32 = 3 as _;
1233     /// let ptr2: *const i32 = 13 as _;
1234     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1235     /// ```
1236     #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1237     #[inline]
1238     pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1239         let pointee_size = mem::size_of::<T>();
1240         assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1241
1242         let d = isize::wrapping_sub(self as _, origin as _);
1243         d.wrapping_div(pointee_size as _)
1244     }
1245
1246     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1247     ///
1248     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1249     /// offset of `3 * size_of::<T>()` bytes.
1250     ///
1251     /// # Safety
1252     ///
1253     /// If any of the following conditions are violated, the result is Undefined
1254     /// Behavior:
1255     ///
1256     /// * Both the starting and resulting pointer must be either in bounds or one
1257     ///   byte past the end of the same allocated object.
1258     ///
1259     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1260     ///
1261     /// * The offset being in bounds cannot rely on "wrapping around" the address
1262     ///   space. That is, the infinite-precision sum must fit in a `usize`.
1263     ///
1264     /// The compiler and standard library generally tries to ensure allocations
1265     /// never reach a size where an offset is a concern. For instance, `Vec`
1266     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1267     /// `vec.as_ptr().add(vec.len())` is always safe.
1268     ///
1269     /// Most platforms fundamentally can't even construct such an allocation.
1270     /// For instance, no known 64-bit platform can ever serve a request
1271     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1272     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1273     /// more than `isize::MAX` bytes with things like Physical Address
1274     /// Extension. As such, memory acquired directly from allocators or memory
1275     /// mapped files *may* be too large to handle with this function.
1276     ///
1277     /// Consider using `wrapping_offset` instead if these constraints are
1278     /// difficult to satisfy. The only advantage of this method is that it
1279     /// enables more aggressive compiler optimizations.
1280     ///
1281     /// # Examples
1282     ///
1283     /// Basic usage:
1284     ///
1285     /// ```
1286     /// let s: &str = "123";
1287     /// let ptr: *const u8 = s.as_ptr();
1288     ///
1289     /// unsafe {
1290     ///     println!("{}", *ptr.add(1) as char);
1291     ///     println!("{}", *ptr.add(2) as char);
1292     /// }
1293     /// ```
1294     #[stable(feature = "pointer_methods", since = "1.26.0")]
1295     #[inline]
1296     pub unsafe fn add(self, count: usize) -> Self
1297         where T: Sized,
1298     {
1299         self.offset(count as isize)
1300     }
1301
1302     /// Calculates the offset from a pointer (convenience for
1303     /// `.offset((count as isize).wrapping_neg())`).
1304     ///
1305     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1306     /// offset of `3 * size_of::<T>()` bytes.
1307     ///
1308     /// # Safety
1309     ///
1310     /// If any of the following conditions are violated, the result is Undefined
1311     /// Behavior:
1312     ///
1313     /// * Both the starting and resulting pointer must be either in bounds or one
1314     ///   byte past the end of the same allocated object.
1315     ///
1316     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1317     ///
1318     /// * The offset being in bounds cannot rely on "wrapping around" the address
1319     ///   space. That is, the infinite-precision sum must fit in a usize.
1320     ///
1321     /// The compiler and standard library generally tries to ensure allocations
1322     /// never reach a size where an offset is a concern. For instance, `Vec`
1323     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1324     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1325     ///
1326     /// Most platforms fundamentally can't even construct such an allocation.
1327     /// For instance, no known 64-bit platform can ever serve a request
1328     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1329     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1330     /// more than `isize::MAX` bytes with things like Physical Address
1331     /// Extension. As such, memory acquired directly from allocators or memory
1332     /// mapped files *may* be too large to handle with this function.
1333     ///
1334     /// Consider using `wrapping_offset` instead if these constraints are
1335     /// difficult to satisfy. The only advantage of this method is that it
1336     /// enables more aggressive compiler optimizations.
1337     ///
1338     /// # Examples
1339     ///
1340     /// Basic usage:
1341     ///
1342     /// ```
1343     /// let s: &str = "123";
1344     ///
1345     /// unsafe {
1346     ///     let end: *const u8 = s.as_ptr().add(3);
1347     ///     println!("{}", *end.sub(1) as char);
1348     ///     println!("{}", *end.sub(2) as char);
1349     /// }
1350     /// ```
1351     #[stable(feature = "pointer_methods", since = "1.26.0")]
1352     #[inline]
1353     pub unsafe fn sub(self, count: usize) -> Self
1354         where T: Sized,
1355     {
1356         self.offset((count as isize).wrapping_neg())
1357     }
1358
1359     /// Calculates the offset from a pointer using wrapping arithmetic.
1360     /// (convenience for `.wrapping_offset(count as isize)`)
1361     ///
1362     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1363     /// offset of `3 * size_of::<T>()` bytes.
1364     ///
1365     /// # Safety
1366     ///
1367     /// The resulting pointer does not need to be in bounds, but it is
1368     /// potentially hazardous to dereference (which requires `unsafe`).
1369     ///
1370     /// Always use `.add(count)` instead when possible, because `add`
1371     /// allows the compiler to optimize better.
1372     ///
1373     /// # Examples
1374     ///
1375     /// Basic usage:
1376     ///
1377     /// ```
1378     /// // Iterate using a raw pointer in increments of two elements
1379     /// let data = [1u8, 2, 3, 4, 5];
1380     /// let mut ptr: *const u8 = data.as_ptr();
1381     /// let step = 2;
1382     /// let end_rounded_up = ptr.wrapping_add(6);
1383     ///
1384     /// // This loop prints "1, 3, 5, "
1385     /// while ptr != end_rounded_up {
1386     ///     unsafe {
1387     ///         print!("{}, ", *ptr);
1388     ///     }
1389     ///     ptr = ptr.wrapping_add(step);
1390     /// }
1391     /// ```
1392     #[stable(feature = "pointer_methods", since = "1.26.0")]
1393     #[inline]
1394     pub fn wrapping_add(self, count: usize) -> Self
1395         where T: Sized,
1396     {
1397         self.wrapping_offset(count as isize)
1398     }
1399
1400     /// Calculates the offset from a pointer using wrapping arithmetic.
1401     /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1402     ///
1403     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1404     /// offset of `3 * size_of::<T>()` bytes.
1405     ///
1406     /// # Safety
1407     ///
1408     /// The resulting pointer does not need to be in bounds, but it is
1409     /// potentially hazardous to dereference (which requires `unsafe`).
1410     ///
1411     /// Always use `.sub(count)` instead when possible, because `sub`
1412     /// allows the compiler to optimize better.
1413     ///
1414     /// # Examples
1415     ///
1416     /// Basic usage:
1417     ///
1418     /// ```
1419     /// // Iterate using a raw pointer in increments of two elements (backwards)
1420     /// let data = [1u8, 2, 3, 4, 5];
1421     /// let mut ptr: *const u8 = data.as_ptr();
1422     /// let start_rounded_down = ptr.wrapping_sub(2);
1423     /// ptr = ptr.wrapping_add(4);
1424     /// let step = 2;
1425     /// // This loop prints "5, 3, 1, "
1426     /// while ptr != start_rounded_down {
1427     ///     unsafe {
1428     ///         print!("{}, ", *ptr);
1429     ///     }
1430     ///     ptr = ptr.wrapping_sub(step);
1431     /// }
1432     /// ```
1433     #[stable(feature = "pointer_methods", since = "1.26.0")]
1434     #[inline]
1435     pub fn wrapping_sub(self, count: usize) -> Self
1436         where T: Sized,
1437     {
1438         self.wrapping_offset((count as isize).wrapping_neg())
1439     }
1440
1441     /// Reads the value from `self` without moving it. This leaves the
1442     /// memory in `self` unchanged.
1443     ///
1444     /// See [`ptr::read`] for safety concerns and examples.
1445     ///
1446     /// [`ptr::read`]: ./ptr/fn.read.html
1447     #[stable(feature = "pointer_methods", since = "1.26.0")]
1448     #[inline]
1449     pub unsafe fn read(self) -> T
1450         where T: Sized,
1451     {
1452         read(self)
1453     }
1454
1455     /// Performs a volatile read of the value from `self` without moving it. This
1456     /// leaves the memory in `self` unchanged.
1457     ///
1458     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1459     /// to not be elided or reordered by the compiler across other volatile
1460     /// operations.
1461     ///
1462     /// See [`ptr::read_volatile`] for safety concerns and examples.
1463     ///
1464     /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
1465     #[stable(feature = "pointer_methods", since = "1.26.0")]
1466     #[inline]
1467     pub unsafe fn read_volatile(self) -> T
1468         where T: Sized,
1469     {
1470         read_volatile(self)
1471     }
1472
1473     /// Reads the value from `self` without moving it. This leaves the
1474     /// memory in `self` unchanged.
1475     ///
1476     /// Unlike `read`, the pointer may be unaligned.
1477     ///
1478     /// See [`ptr::read_unaligned`] for safety concerns and examples.
1479     ///
1480     /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
1481     #[stable(feature = "pointer_methods", since = "1.26.0")]
1482     #[inline]
1483     pub unsafe fn read_unaligned(self) -> T
1484         where T: Sized,
1485     {
1486         read_unaligned(self)
1487     }
1488
1489     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1490     /// and destination may overlap.
1491     ///
1492     /// NOTE: this has the *same* argument order as [`ptr::copy`].
1493     ///
1494     /// See [`ptr::copy`] for safety concerns and examples.
1495     ///
1496     /// [`ptr::copy`]: ./ptr/fn.copy.html
1497     #[stable(feature = "pointer_methods", since = "1.26.0")]
1498     #[inline]
1499     pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1500         where T: Sized,
1501     {
1502         copy(self, dest, count)
1503     }
1504
1505     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1506     /// and destination may *not* overlap.
1507     ///
1508     /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1509     ///
1510     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1511     ///
1512     /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
1513     #[stable(feature = "pointer_methods", since = "1.26.0")]
1514     #[inline]
1515     pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1516         where T: Sized,
1517     {
1518         copy_nonoverlapping(self, dest, count)
1519     }
1520
1521     /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1522     /// `align`.
1523     ///
1524     /// If it is not possible to align the pointer, the implementation returns
1525     /// `usize::max_value()`.
1526     ///
1527     /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1528     /// used with the `offset` or `offset_to` methods.
1529     ///
1530     /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
1531     /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1532     /// the returned offset is correct in all terms other than alignment.
1533     ///
1534     /// # Panics
1535     ///
1536     /// The function panics if `align` is not a power-of-two.
1537     ///
1538     /// # Examples
1539     ///
1540     /// Accessing adjacent `u8` as `u16`
1541     ///
1542     /// ```
1543     /// # fn foo(n: usize) {
1544     /// # use std::mem::align_of;
1545     /// # unsafe {
1546     /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1547     /// let ptr = &x[n] as *const u8;
1548     /// let offset = ptr.align_offset(align_of::<u16>());
1549     /// if offset < x.len() - n - 1 {
1550     ///     let u16_ptr = ptr.add(offset) as *const u16;
1551     ///     assert_ne!(*u16_ptr, 500);
1552     /// } else {
1553     ///     // while the pointer can be aligned via `offset`, it would point
1554     ///     // outside the allocation
1555     /// }
1556     /// # } }
1557     /// ```
1558     #[stable(feature = "align_offset", since = "1.36.0")]
1559     pub fn align_offset(self, align: usize) -> usize where T: Sized {
1560         if !align.is_power_of_two() {
1561             panic!("align_offset: align is not a power-of-two");
1562         }
1563         unsafe {
1564             align_offset(self, align)
1565         }
1566     }
1567 }
1568
1569
1570 #[lang = "mut_ptr"]
1571 impl<T: ?Sized> *mut T {
1572     /// Returns `true` if the pointer is null.
1573     ///
1574     /// Note that unsized types have many possible null pointers, as only the
1575     /// raw data pointer is considered, not their length, vtable, etc.
1576     /// Therefore, two pointers that are null may still not compare equal to
1577     /// each other.
1578     ///
1579     /// # Examples
1580     ///
1581     /// Basic usage:
1582     ///
1583     /// ```
1584     /// let mut s = [1, 2, 3];
1585     /// let ptr: *mut u32 = s.as_mut_ptr();
1586     /// assert!(!ptr.is_null());
1587     /// ```
1588     #[stable(feature = "rust1", since = "1.0.0")]
1589     #[inline]
1590     pub fn is_null(self) -> bool {
1591         // Compare via a cast to a thin pointer, so fat pointers are only
1592         // considering their "data" part for null-ness.
1593         (self as *mut u8) == null_mut()
1594     }
1595
1596     /// Returns `None` if the pointer is null, or else returns a reference to
1597     /// the value wrapped in `Some`.
1598     ///
1599     /// # Safety
1600     ///
1601     /// While this method and its mutable counterpart are useful for
1602     /// null-safety, it is important to note that this is still an unsafe
1603     /// operation because the returned value could be pointing to invalid
1604     /// memory.
1605     ///
1606     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1607     /// not necessarily reflect the actual lifetime of the data.
1608     ///
1609     /// # Examples
1610     ///
1611     /// Basic usage:
1612     ///
1613     /// ```
1614     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1615     ///
1616     /// unsafe {
1617     ///     if let Some(val_back) = ptr.as_ref() {
1618     ///         println!("We got back the value: {}!", val_back);
1619     ///     }
1620     /// }
1621     /// ```
1622     ///
1623     /// # Null-unchecked version
1624     ///
1625     /// If you are sure the pointer can never be null and are looking for some kind of
1626     /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1627     /// dereference the pointer directly.
1628     ///
1629     /// ```
1630     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1631     ///
1632     /// unsafe {
1633     ///     let val_back = &*ptr;
1634     ///     println!("We got back the value: {}!", val_back);
1635     /// }
1636     /// ```
1637     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1638     #[inline]
1639     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1640         if self.is_null() {
1641             None
1642         } else {
1643             Some(&*self)
1644         }
1645     }
1646
1647     /// Calculates the offset from a pointer.
1648     ///
1649     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1650     /// offset of `3 * size_of::<T>()` bytes.
1651     ///
1652     /// # Safety
1653     ///
1654     /// If any of the following conditions are violated, the result is Undefined
1655     /// Behavior:
1656     ///
1657     /// * Both the starting and resulting pointer must be either in bounds or one
1658     ///   byte past the end of the same allocated object.
1659     ///
1660     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1661     ///
1662     /// * The offset being in bounds cannot rely on "wrapping around" the address
1663     ///   space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1664     ///
1665     /// The compiler and standard library generally tries to ensure allocations
1666     /// never reach a size where an offset is a concern. For instance, `Vec`
1667     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1668     /// `vec.as_ptr().add(vec.len())` is always safe.
1669     ///
1670     /// Most platforms fundamentally can't even construct such an allocation.
1671     /// For instance, no known 64-bit platform can ever serve a request
1672     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1673     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1674     /// more than `isize::MAX` bytes with things like Physical Address
1675     /// Extension. As such, memory acquired directly from allocators or memory
1676     /// mapped files *may* be too large to handle with this function.
1677     ///
1678     /// Consider using `wrapping_offset` instead if these constraints are
1679     /// difficult to satisfy. The only advantage of this method is that it
1680     /// enables more aggressive compiler optimizations.
1681     ///
1682     /// # Examples
1683     ///
1684     /// Basic usage:
1685     ///
1686     /// ```
1687     /// let mut s = [1, 2, 3];
1688     /// let ptr: *mut u32 = s.as_mut_ptr();
1689     ///
1690     /// unsafe {
1691     ///     println!("{}", *ptr.offset(1));
1692     ///     println!("{}", *ptr.offset(2));
1693     /// }
1694     /// ```
1695     #[stable(feature = "rust1", since = "1.0.0")]
1696     #[inline]
1697     pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1698         intrinsics::offset(self, count) as *mut T
1699     }
1700
1701     /// Calculates the offset from a pointer using wrapping arithmetic.
1702     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1703     /// offset of `3 * size_of::<T>()` bytes.
1704     ///
1705     /// # Safety
1706     ///
1707     /// The resulting pointer does not need to be in bounds, but it is
1708     /// potentially hazardous to dereference (which requires `unsafe`).
1709     /// In particular, the resulting pointer may *not* be used to access a
1710     /// different allocated object than the one `self` points to. In other
1711     /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1712     /// *not* the same as `y`, and dereferencing it is undefined behavior
1713     /// unless `x` and `y` point into the same allocated object.
1714     ///
1715     /// Always use `.offset(count)` instead when possible, because `offset`
1716     /// allows the compiler to optimize better. If you need to cross object
1717     /// boundaries, cast the pointer to an integer and do the arithmetic there.
1718     ///
1719     /// # Examples
1720     ///
1721     /// Basic usage:
1722     ///
1723     /// ```
1724     /// // Iterate using a raw pointer in increments of two elements
1725     /// let mut data = [1u8, 2, 3, 4, 5];
1726     /// let mut ptr: *mut u8 = data.as_mut_ptr();
1727     /// let step = 2;
1728     /// let end_rounded_up = ptr.wrapping_offset(6);
1729     ///
1730     /// while ptr != end_rounded_up {
1731     ///     unsafe {
1732     ///         *ptr = 0;
1733     ///     }
1734     ///     ptr = ptr.wrapping_offset(step);
1735     /// }
1736     /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1737     /// ```
1738     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1739     #[inline]
1740     pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1741         unsafe {
1742             intrinsics::arith_offset(self, count) as *mut T
1743         }
1744     }
1745
1746     /// Returns `None` if the pointer is null, or else returns a mutable
1747     /// reference to the value wrapped in `Some`.
1748     ///
1749     /// # Safety
1750     ///
1751     /// As with `as_ref`, this is unsafe because it cannot verify the validity
1752     /// of the returned pointer, nor can it ensure that the lifetime `'a`
1753     /// returned is indeed a valid lifetime for the contained data.
1754     ///
1755     /// # Examples
1756     ///
1757     /// Basic usage:
1758     ///
1759     /// ```
1760     /// let mut s = [1, 2, 3];
1761     /// let ptr: *mut u32 = s.as_mut_ptr();
1762     /// let first_value = unsafe { ptr.as_mut().unwrap() };
1763     /// *first_value = 4;
1764     /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1765     /// ```
1766     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1767     #[inline]
1768     pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1769         if self.is_null() {
1770             None
1771         } else {
1772             Some(&mut *self)
1773         }
1774     }
1775
1776     /// Calculates the distance between two pointers. The returned value is in
1777     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1778     ///
1779     /// This function is the inverse of [`offset`].
1780     ///
1781     /// [`offset`]: #method.offset-1
1782     /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
1783     ///
1784     /// # Safety
1785     ///
1786     /// If any of the following conditions are violated, the result is Undefined
1787     /// Behavior:
1788     ///
1789     /// * Both the starting and other pointer must be either in bounds or one
1790     ///   byte past the end of the same allocated object.
1791     ///
1792     /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1793     ///
1794     /// * The distance between the pointers, in bytes, must be an exact multiple
1795     ///   of the size of `T`.
1796     ///
1797     /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1798     ///
1799     /// The compiler and standard library generally try to ensure allocations
1800     /// never reach a size where an offset is a concern. For instance, `Vec`
1801     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1802     /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1803     ///
1804     /// Most platforms fundamentally can't even construct such an allocation.
1805     /// For instance, no known 64-bit platform can ever serve a request
1806     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1807     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1808     /// more than `isize::MAX` bytes with things like Physical Address
1809     /// Extension. As such, memory acquired directly from allocators or memory
1810     /// mapped files *may* be too large to handle with this function.
1811     ///
1812     /// Consider using [`wrapping_offset_from`] instead if these constraints are
1813     /// difficult to satisfy. The only advantage of this method is that it
1814     /// enables more aggressive compiler optimizations.
1815     ///
1816     /// # Panics
1817     ///
1818     /// This function panics if `T` is a Zero-Sized Type ("ZST").
1819     ///
1820     /// # Examples
1821     ///
1822     /// Basic usage:
1823     ///
1824     /// ```
1825     /// #![feature(ptr_offset_from)]
1826     ///
1827     /// let mut a = [0; 5];
1828     /// let ptr1: *mut i32 = &mut a[1];
1829     /// let ptr2: *mut i32 = &mut a[3];
1830     /// unsafe {
1831     ///     assert_eq!(ptr2.offset_from(ptr1), 2);
1832     ///     assert_eq!(ptr1.offset_from(ptr2), -2);
1833     ///     assert_eq!(ptr1.offset(2), ptr2);
1834     ///     assert_eq!(ptr2.offset(-2), ptr1);
1835     /// }
1836     /// ```
1837     #[unstable(feature = "ptr_offset_from", issue = "41079")]
1838     #[inline]
1839     pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1840         (self as *const T).offset_from(origin)
1841     }
1842
1843     /// Calculates the distance between two pointers. The returned value is in
1844     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1845     ///
1846     /// If the address different between the two pointers is not a multiple of
1847     /// `mem::size_of::<T>()` then the result of the division is rounded towards
1848     /// zero.
1849     ///
1850     /// Though this method is safe for any two pointers, note that its result
1851     /// will be mostly useless if the two pointers aren't into the same allocated
1852     /// object, for example if they point to two different local variables.
1853     ///
1854     /// # Panics
1855     ///
1856     /// This function panics if `T` is a zero-sized type.
1857     ///
1858     /// # Examples
1859     ///
1860     /// Basic usage:
1861     ///
1862     /// ```
1863     /// #![feature(ptr_wrapping_offset_from)]
1864     ///
1865     /// let mut a = [0; 5];
1866     /// let ptr1: *mut i32 = &mut a[1];
1867     /// let ptr2: *mut i32 = &mut a[3];
1868     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1869     /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1870     /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1871     /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1872     ///
1873     /// let ptr1: *mut i32 = 3 as _;
1874     /// let ptr2: *mut i32 = 13 as _;
1875     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1876     /// ```
1877     #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1878     #[inline]
1879     pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1880         (self as *const T).wrapping_offset_from(origin)
1881     }
1882
1883     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1884     ///
1885     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1886     /// offset of `3 * size_of::<T>()` bytes.
1887     ///
1888     /// # Safety
1889     ///
1890     /// If any of the following conditions are violated, the result is Undefined
1891     /// Behavior:
1892     ///
1893     /// * Both the starting and resulting pointer must be either in bounds or one
1894     ///   byte past the end of the same allocated object.
1895     ///
1896     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1897     ///
1898     /// * The offset being in bounds cannot rely on "wrapping around" the address
1899     ///   space. That is, the infinite-precision sum must fit in a `usize`.
1900     ///
1901     /// The compiler and standard library generally tries to ensure allocations
1902     /// never reach a size where an offset is a concern. For instance, `Vec`
1903     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1904     /// `vec.as_ptr().add(vec.len())` is always safe.
1905     ///
1906     /// Most platforms fundamentally can't even construct such an allocation.
1907     /// For instance, no known 64-bit platform can ever serve a request
1908     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1909     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1910     /// more than `isize::MAX` bytes with things like Physical Address
1911     /// Extension. As such, memory acquired directly from allocators or memory
1912     /// mapped files *may* be too large to handle with this function.
1913     ///
1914     /// Consider using `wrapping_offset` instead if these constraints are
1915     /// difficult to satisfy. The only advantage of this method is that it
1916     /// enables more aggressive compiler optimizations.
1917     ///
1918     /// # Examples
1919     ///
1920     /// Basic usage:
1921     ///
1922     /// ```
1923     /// let s: &str = "123";
1924     /// let ptr: *const u8 = s.as_ptr();
1925     ///
1926     /// unsafe {
1927     ///     println!("{}", *ptr.add(1) as char);
1928     ///     println!("{}", *ptr.add(2) as char);
1929     /// }
1930     /// ```
1931     #[stable(feature = "pointer_methods", since = "1.26.0")]
1932     #[inline]
1933     pub unsafe fn add(self, count: usize) -> Self
1934         where T: Sized,
1935     {
1936         self.offset(count as isize)
1937     }
1938
1939     /// Calculates the offset from a pointer (convenience for
1940     /// `.offset((count as isize).wrapping_neg())`).
1941     ///
1942     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1943     /// offset of `3 * size_of::<T>()` bytes.
1944     ///
1945     /// # Safety
1946     ///
1947     /// If any of the following conditions are violated, the result is Undefined
1948     /// Behavior:
1949     ///
1950     /// * Both the starting and resulting pointer must be either in bounds or one
1951     ///   byte past the end of the same allocated object.
1952     ///
1953     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1954     ///
1955     /// * The offset being in bounds cannot rely on "wrapping around" the address
1956     ///   space. That is, the infinite-precision sum must fit in a usize.
1957     ///
1958     /// The compiler and standard library generally tries to ensure allocations
1959     /// never reach a size where an offset is a concern. For instance, `Vec`
1960     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1961     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1962     ///
1963     /// Most platforms fundamentally can't even construct such an allocation.
1964     /// For instance, no known 64-bit platform can ever serve a request
1965     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1966     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1967     /// more than `isize::MAX` bytes with things like Physical Address
1968     /// Extension. As such, memory acquired directly from allocators or memory
1969     /// mapped files *may* be too large to handle with this function.
1970     ///
1971     /// Consider using `wrapping_offset` instead if these constraints are
1972     /// difficult to satisfy. The only advantage of this method is that it
1973     /// enables more aggressive compiler optimizations.
1974     ///
1975     /// # Examples
1976     ///
1977     /// Basic usage:
1978     ///
1979     /// ```
1980     /// let s: &str = "123";
1981     ///
1982     /// unsafe {
1983     ///     let end: *const u8 = s.as_ptr().add(3);
1984     ///     println!("{}", *end.sub(1) as char);
1985     ///     println!("{}", *end.sub(2) as char);
1986     /// }
1987     /// ```
1988     #[stable(feature = "pointer_methods", since = "1.26.0")]
1989     #[inline]
1990     pub unsafe fn sub(self, count: usize) -> Self
1991         where T: Sized,
1992     {
1993         self.offset((count as isize).wrapping_neg())
1994     }
1995
1996     /// Calculates the offset from a pointer using wrapping arithmetic.
1997     /// (convenience for `.wrapping_offset(count as isize)`)
1998     ///
1999     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2000     /// offset of `3 * size_of::<T>()` bytes.
2001     ///
2002     /// # Safety
2003     ///
2004     /// The resulting pointer does not need to be in bounds, but it is
2005     /// potentially hazardous to dereference (which requires `unsafe`).
2006     ///
2007     /// Always use `.add(count)` instead when possible, because `add`
2008     /// allows the compiler to optimize better.
2009     ///
2010     /// # Examples
2011     ///
2012     /// Basic usage:
2013     ///
2014     /// ```
2015     /// // Iterate using a raw pointer in increments of two elements
2016     /// let data = [1u8, 2, 3, 4, 5];
2017     /// let mut ptr: *const u8 = data.as_ptr();
2018     /// let step = 2;
2019     /// let end_rounded_up = ptr.wrapping_add(6);
2020     ///
2021     /// // This loop prints "1, 3, 5, "
2022     /// while ptr != end_rounded_up {
2023     ///     unsafe {
2024     ///         print!("{}, ", *ptr);
2025     ///     }
2026     ///     ptr = ptr.wrapping_add(step);
2027     /// }
2028     /// ```
2029     #[stable(feature = "pointer_methods", since = "1.26.0")]
2030     #[inline]
2031     pub fn wrapping_add(self, count: usize) -> Self
2032         where T: Sized,
2033     {
2034         self.wrapping_offset(count as isize)
2035     }
2036
2037     /// Calculates the offset from a pointer using wrapping arithmetic.
2038     /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
2039     ///
2040     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2041     /// offset of `3 * size_of::<T>()` bytes.
2042     ///
2043     /// # Safety
2044     ///
2045     /// The resulting pointer does not need to be in bounds, but it is
2046     /// potentially hazardous to dereference (which requires `unsafe`).
2047     ///
2048     /// Always use `.sub(count)` instead when possible, because `sub`
2049     /// allows the compiler to optimize better.
2050     ///
2051     /// # Examples
2052     ///
2053     /// Basic usage:
2054     ///
2055     /// ```
2056     /// // Iterate using a raw pointer in increments of two elements (backwards)
2057     /// let data = [1u8, 2, 3, 4, 5];
2058     /// let mut ptr: *const u8 = data.as_ptr();
2059     /// let start_rounded_down = ptr.wrapping_sub(2);
2060     /// ptr = ptr.wrapping_add(4);
2061     /// let step = 2;
2062     /// // This loop prints "5, 3, 1, "
2063     /// while ptr != start_rounded_down {
2064     ///     unsafe {
2065     ///         print!("{}, ", *ptr);
2066     ///     }
2067     ///     ptr = ptr.wrapping_sub(step);
2068     /// }
2069     /// ```
2070     #[stable(feature = "pointer_methods", since = "1.26.0")]
2071     #[inline]
2072     pub fn wrapping_sub(self, count: usize) -> Self
2073         where T: Sized,
2074     {
2075         self.wrapping_offset((count as isize).wrapping_neg())
2076     }
2077
2078     /// Reads the value from `self` without moving it. This leaves the
2079     /// memory in `self` unchanged.
2080     ///
2081     /// See [`ptr::read`] for safety concerns and examples.
2082     ///
2083     /// [`ptr::read`]: ./ptr/fn.read.html
2084     #[stable(feature = "pointer_methods", since = "1.26.0")]
2085     #[inline]
2086     pub unsafe fn read(self) -> T
2087         where T: Sized,
2088     {
2089         read(self)
2090     }
2091
2092     /// Performs a volatile read of the value from `self` without moving it. This
2093     /// leaves the memory in `self` unchanged.
2094     ///
2095     /// Volatile operations are intended to act on I/O memory, and are guaranteed
2096     /// to not be elided or reordered by the compiler across other volatile
2097     /// operations.
2098     ///
2099     /// See [`ptr::read_volatile`] for safety concerns and examples.
2100     ///
2101     /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
2102     #[stable(feature = "pointer_methods", since = "1.26.0")]
2103     #[inline]
2104     pub unsafe fn read_volatile(self) -> T
2105         where T: Sized,
2106     {
2107         read_volatile(self)
2108     }
2109
2110     /// Reads the value from `self` without moving it. This leaves the
2111     /// memory in `self` unchanged.
2112     ///
2113     /// Unlike `read`, the pointer may be unaligned.
2114     ///
2115     /// See [`ptr::read_unaligned`] for safety concerns and examples.
2116     ///
2117     /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
2118     #[stable(feature = "pointer_methods", since = "1.26.0")]
2119     #[inline]
2120     pub unsafe fn read_unaligned(self) -> T
2121         where T: Sized,
2122     {
2123         read_unaligned(self)
2124     }
2125
2126     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2127     /// and destination may overlap.
2128     ///
2129     /// NOTE: this has the *same* argument order as [`ptr::copy`].
2130     ///
2131     /// See [`ptr::copy`] for safety concerns and examples.
2132     ///
2133     /// [`ptr::copy`]: ./ptr/fn.copy.html
2134     #[stable(feature = "pointer_methods", since = "1.26.0")]
2135     #[inline]
2136     pub unsafe fn copy_to(self, dest: *mut T, count: usize)
2137         where T: Sized,
2138     {
2139         copy(self, dest, count)
2140     }
2141
2142     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2143     /// and destination may *not* overlap.
2144     ///
2145     /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
2146     ///
2147     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2148     ///
2149     /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2150     #[stable(feature = "pointer_methods", since = "1.26.0")]
2151     #[inline]
2152     pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
2153         where T: Sized,
2154     {
2155         copy_nonoverlapping(self, dest, count)
2156     }
2157
2158     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2159     /// and destination may overlap.
2160     ///
2161     /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
2162     ///
2163     /// See [`ptr::copy`] for safety concerns and examples.
2164     ///
2165     /// [`ptr::copy`]: ./ptr/fn.copy.html
2166     #[stable(feature = "pointer_methods", since = "1.26.0")]
2167     #[inline]
2168     pub unsafe fn copy_from(self, src: *const T, count: usize)
2169         where T: Sized,
2170     {
2171         copy(src, self, count)
2172     }
2173
2174     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2175     /// and destination may *not* overlap.
2176     ///
2177     /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
2178     ///
2179     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2180     ///
2181     /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2182     #[stable(feature = "pointer_methods", since = "1.26.0")]
2183     #[inline]
2184     pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
2185         where T: Sized,
2186     {
2187         copy_nonoverlapping(src, self, count)
2188     }
2189
2190     /// Executes the destructor (if any) of the pointed-to value.
2191     ///
2192     /// See [`ptr::drop_in_place`] for safety concerns and examples.
2193     ///
2194     /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
2195     #[stable(feature = "pointer_methods", since = "1.26.0")]
2196     #[inline]
2197     pub unsafe fn drop_in_place(self) {
2198         drop_in_place(self)
2199     }
2200
2201     /// Overwrites a memory location with the given value without reading or
2202     /// dropping the old value.
2203     ///
2204     /// See [`ptr::write`] for safety concerns and examples.
2205     ///
2206     /// [`ptr::write`]: ./ptr/fn.write.html
2207     #[stable(feature = "pointer_methods", since = "1.26.0")]
2208     #[inline]
2209     pub unsafe fn write(self, val: T)
2210         where T: Sized,
2211     {
2212         write(self, val)
2213     }
2214
2215     /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
2216     /// bytes of memory starting at `self` to `val`.
2217     ///
2218     /// See [`ptr::write_bytes`] for safety concerns and examples.
2219     ///
2220     /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
2221     #[stable(feature = "pointer_methods", since = "1.26.0")]
2222     #[inline]
2223     pub unsafe fn write_bytes(self, val: u8, count: usize)
2224         where T: Sized,
2225     {
2226         write_bytes(self, val, count)
2227     }
2228
2229     /// Performs a volatile write of a memory location with the given value without
2230     /// reading or dropping the old value.
2231     ///
2232     /// Volatile operations are intended to act on I/O memory, and are guaranteed
2233     /// to not be elided or reordered by the compiler across other volatile
2234     /// operations.
2235     ///
2236     /// See [`ptr::write_volatile`] for safety concerns and examples.
2237     ///
2238     /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
2239     #[stable(feature = "pointer_methods", since = "1.26.0")]
2240     #[inline]
2241     pub unsafe fn write_volatile(self, val: T)
2242         where T: Sized,
2243     {
2244         write_volatile(self, val)
2245     }
2246
2247     /// Overwrites a memory location with the given value without reading or
2248     /// dropping the old value.
2249     ///
2250     /// Unlike `write`, the pointer may be unaligned.
2251     ///
2252     /// See [`ptr::write_unaligned`] for safety concerns and examples.
2253     ///
2254     /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
2255     #[stable(feature = "pointer_methods", since = "1.26.0")]
2256     #[inline]
2257     pub unsafe fn write_unaligned(self, val: T)
2258         where T: Sized,
2259     {
2260         write_unaligned(self, val)
2261     }
2262
2263     /// Replaces the value at `self` with `src`, returning the old
2264     /// value, without dropping either.
2265     ///
2266     /// See [`ptr::replace`] for safety concerns and examples.
2267     ///
2268     /// [`ptr::replace`]: ./ptr/fn.replace.html
2269     #[stable(feature = "pointer_methods", since = "1.26.0")]
2270     #[inline]
2271     pub unsafe fn replace(self, src: T) -> T
2272         where T: Sized,
2273     {
2274         replace(self, src)
2275     }
2276
2277     /// Swaps the values at two mutable locations of the same type, without
2278     /// deinitializing either. They may overlap, unlike `mem::swap` which is
2279     /// otherwise equivalent.
2280     ///
2281     /// See [`ptr::swap`] for safety concerns and examples.
2282     ///
2283     /// [`ptr::swap`]: ./ptr/fn.swap.html
2284     #[stable(feature = "pointer_methods", since = "1.26.0")]
2285     #[inline]
2286     pub unsafe fn swap(self, with: *mut T)
2287         where T: Sized,
2288     {
2289         swap(self, with)
2290     }
2291
2292     /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
2293     /// `align`.
2294     ///
2295     /// If it is not possible to align the pointer, the implementation returns
2296     /// `usize::max_value()`.
2297     ///
2298     /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
2299     /// used with the `offset` or `offset_to` methods.
2300     ///
2301     /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
2302     /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
2303     /// the returned offset is correct in all terms other than alignment.
2304     ///
2305     /// # Panics
2306     ///
2307     /// The function panics if `align` is not a power-of-two.
2308     ///
2309     /// # Examples
2310     ///
2311     /// Accessing adjacent `u8` as `u16`
2312     ///
2313     /// ```
2314     /// # fn foo(n: usize) {
2315     /// # use std::mem::align_of;
2316     /// # unsafe {
2317     /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
2318     /// let ptr = &x[n] as *const u8;
2319     /// let offset = ptr.align_offset(align_of::<u16>());
2320     /// if offset < x.len() - n - 1 {
2321     ///     let u16_ptr = ptr.add(offset) as *const u16;
2322     ///     assert_ne!(*u16_ptr, 500);
2323     /// } else {
2324     ///     // while the pointer can be aligned via `offset`, it would point
2325     ///     // outside the allocation
2326     /// }
2327     /// # } }
2328     /// ```
2329     #[stable(feature = "align_offset", since = "1.36.0")]
2330     pub fn align_offset(self, align: usize) -> usize where T: Sized {
2331         if !align.is_power_of_two() {
2332             panic!("align_offset: align is not a power-of-two");
2333         }
2334         unsafe {
2335             align_offset(self, align)
2336         }
2337     }
2338 }
2339
2340 /// Align pointer `p`.
2341 ///
2342 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
2343 /// to pointer `p` so that pointer `p` would get aligned to `a`.
2344 ///
2345 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
2346 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2347 /// constants.
2348 ///
2349 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2350 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2351 /// than trying to adapt this to accommodate that change.
2352 ///
2353 /// Any questions go to @nagisa.
2354 #[lang="align_offset"]
2355 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2356     /// Calculate multiplicative modular inverse of `x` modulo `m`.
2357     ///
2358     /// This implementation is tailored for align_offset and has following preconditions:
2359     ///
2360     /// * `m` is a power-of-two;
2361     /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2362     ///
2363     /// Implementation of this function shall not panic. Ever.
2364     #[inline]
2365     fn mod_inv(x: usize, m: usize) -> usize {
2366         /// Multiplicative modular inverse table modulo 2⁴ = 16.
2367         ///
2368         /// Note, that this table does not contain values where inverse does not exist (i.e., for
2369         /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2370         const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2371         /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2372         const INV_TABLE_MOD: usize = 16;
2373         /// INV_TABLE_MOD²
2374         const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
2375
2376         let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
2377         if m <= INV_TABLE_MOD {
2378             table_inverse & (m - 1)
2379         } else {
2380             // We iterate "up" using the following formula:
2381             //
2382             // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2383             //
2384             // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
2385             let mut inverse = table_inverse;
2386             let mut going_mod = INV_TABLE_MOD_SQUARED;
2387             loop {
2388                 // y = y * (2 - xy) mod n
2389                 //
2390                 // Note, that we use wrapping operations here intentionally – the original formula
2391                 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
2392                 // usize::max_value()` instead, because we take the result `mod n` at the end
2393                 // anyway.
2394                 inverse = inverse.wrapping_mul(
2395                     2usize.wrapping_sub(x.wrapping_mul(inverse))
2396                 ) & (going_mod - 1);
2397                 if going_mod > m {
2398                     return inverse & (m - 1);
2399                 }
2400                 going_mod = going_mod.wrapping_mul(going_mod);
2401             }
2402         }
2403     }
2404
2405     let stride = mem::size_of::<T>();
2406     let a_minus_one = a.wrapping_sub(1);
2407     let pmoda = p as usize & a_minus_one;
2408
2409     if pmoda == 0 {
2410         // Already aligned. Yay!
2411         return 0;
2412     }
2413
2414     if stride <= 1 {
2415         return if stride == 0 {
2416             // If the pointer is not aligned, and the element is zero-sized, then no amount of
2417             // elements will ever align the pointer.
2418             !0
2419         } else {
2420             a.wrapping_sub(pmoda)
2421         };
2422     }
2423
2424     let smoda = stride & a_minus_one;
2425     // a is power-of-two so cannot be 0. stride = 0 is handled above.
2426     let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
2427     let gcd = 1usize << gcdpow;
2428
2429     if p as usize & (gcd - 1) == 0 {
2430         // This branch solves for the following linear congruence equation:
2431         //
2432         // $$ p + so ≡ 0 mod a $$
2433         //
2434         // $p$ here is the pointer value, $s$ – stride of `T`, $o$ offset in `T`s, and $a$ – the
2435         // requested alignment.
2436         //
2437         // g = gcd(a, s)
2438         // o = (a - (p mod a))/g * ((s/g)⁻¹ mod a)
2439         //
2440         // The first term is “the relative alignment of p to a”, the second term is “how does
2441         // incrementing p by s bytes change the relative alignment of p”. Division by `g` is
2442         // necessary to make this equation well formed if $a$ and $s$ are not co-prime.
2443         //
2444         // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
2445         // to take the result $o mod lcm(s, a)$. We can replace $lcm(s, a)$ with just a $a / g$.
2446         let j = a.wrapping_sub(pmoda) >> gcdpow;
2447         let k = smoda >> gcdpow;
2448         return intrinsics::unchecked_rem(j.wrapping_mul(mod_inv(k, a)), a >> gcdpow);
2449     }
2450
2451     // Cannot be aligned at all.
2452     usize::max_value()
2453 }
2454
2455
2456
2457 // Equality for pointers
2458 #[stable(feature = "rust1", since = "1.0.0")]
2459 impl<T: ?Sized> PartialEq for *const T {
2460     #[inline]
2461     fn eq(&self, other: &*const T) -> bool { *self == *other }
2462 }
2463
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 impl<T: ?Sized> Eq for *const T {}
2466
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 impl<T: ?Sized> PartialEq for *mut T {
2469     #[inline]
2470     fn eq(&self, other: &*mut T) -> bool { *self == *other }
2471 }
2472
2473 #[stable(feature = "rust1", since = "1.0.0")]
2474 impl<T: ?Sized> Eq for *mut T {}
2475
2476 /// Compares raw pointers for equality.
2477 ///
2478 /// This is the same as using the `==` operator, but less generic:
2479 /// the arguments have to be `*const T` raw pointers,
2480 /// not anything that implements `PartialEq`.
2481 ///
2482 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2483 /// by their address rather than comparing the values they point to
2484 /// (which is what the `PartialEq for &T` implementation does).
2485 ///
2486 /// # Examples
2487 ///
2488 /// ```
2489 /// use std::ptr;
2490 ///
2491 /// let five = 5;
2492 /// let other_five = 5;
2493 /// let five_ref = &five;
2494 /// let same_five_ref = &five;
2495 /// let other_five_ref = &other_five;
2496 ///
2497 /// assert!(five_ref == same_five_ref);
2498 /// assert!(ptr::eq(five_ref, same_five_ref));
2499 ///
2500 /// assert!(five_ref == other_five_ref);
2501 /// assert!(!ptr::eq(five_ref, other_five_ref));
2502 /// ```
2503 ///
2504 /// Slices are also compared by their length (fat pointers):
2505 ///
2506 /// ```
2507 /// let a = [1, 2, 3];
2508 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
2509 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
2510 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
2511 /// ```
2512 ///
2513 /// Traits are also compared by their implementation:
2514 ///
2515 /// ```
2516 /// #[repr(transparent)]
2517 /// struct Wrapper { member: i32 }
2518 ///
2519 /// trait Trait {}
2520 /// impl Trait for Wrapper {}
2521 /// impl Trait for i32 {}
2522 ///
2523 /// fn main() {
2524 ///     let wrapper = Wrapper { member: 10 };
2525 ///
2526 ///     // Pointers have equal addresses.
2527 ///     assert!(std::ptr::eq(
2528 ///         &wrapper as *const Wrapper as *const u8,
2529 ///         &wrapper.member as *const i32 as *const u8
2530 ///     ));
2531 ///
2532 ///     // Objects have equal addresses, but `Trait` has different implementations.
2533 ///     assert!(!std::ptr::eq(
2534 ///         &wrapper as &dyn Trait,
2535 ///         &wrapper.member as &dyn Trait,
2536 ///     ));
2537 ///     assert!(!std::ptr::eq(
2538 ///         &wrapper as &dyn Trait as *const dyn Trait,
2539 ///         &wrapper.member as &dyn Trait as *const dyn Trait,
2540 ///     ));
2541 ///
2542 ///     // Converting the reference to a `*const u8` compares by address.
2543 ///     assert!(std::ptr::eq(
2544 ///         &wrapper as &dyn Trait as *const dyn Trait as *const u8,
2545 ///         &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
2546 ///     ));
2547 /// }
2548 /// ```
2549 #[stable(feature = "ptr_eq", since = "1.17.0")]
2550 #[inline]
2551 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2552     a == b
2553 }
2554
2555 /// Hash a raw pointer.
2556 ///
2557 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
2558 /// by its address rather than the value it points to
2559 /// (which is what the `Hash for &T` implementation does).
2560 ///
2561 /// # Examples
2562 ///
2563 /// ```
2564 /// use std::collections::hash_map::DefaultHasher;
2565 /// use std::hash::{Hash, Hasher};
2566 /// use std::ptr;
2567 ///
2568 /// let five = 5;
2569 /// let five_ref = &five;
2570 ///
2571 /// let mut hasher = DefaultHasher::new();
2572 /// ptr::hash(five_ref, &mut hasher);
2573 /// let actual = hasher.finish();
2574 ///
2575 /// let mut hasher = DefaultHasher::new();
2576 /// (five_ref as *const i32).hash(&mut hasher);
2577 /// let expected = hasher.finish();
2578 ///
2579 /// assert_eq!(actual, expected);
2580 /// ```
2581 #[stable(feature = "ptr_hash", since = "1.35.0")]
2582 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
2583     use crate::hash::Hash;
2584     hashee.hash(into);
2585 }
2586
2587 // Impls for function pointers
2588 macro_rules! fnptr_impls_safety_abi {
2589     ($FnTy: ty, $($Arg: ident),*) => {
2590         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2591         impl<Ret, $($Arg),*> PartialEq for $FnTy {
2592             #[inline]
2593             fn eq(&self, other: &Self) -> bool {
2594                 *self as usize == *other as usize
2595             }
2596         }
2597
2598         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2599         impl<Ret, $($Arg),*> Eq for $FnTy {}
2600
2601         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2602         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2603             #[inline]
2604             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2605                 (*self as usize).partial_cmp(&(*other as usize))
2606             }
2607         }
2608
2609         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2610         impl<Ret, $($Arg),*> Ord for $FnTy {
2611             #[inline]
2612             fn cmp(&self, other: &Self) -> Ordering {
2613                 (*self as usize).cmp(&(*other as usize))
2614             }
2615         }
2616
2617         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2618         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2619             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2620                 state.write_usize(*self as usize)
2621             }
2622         }
2623
2624         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2625         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2626             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2627                 fmt::Pointer::fmt(&(*self as *const ()), f)
2628             }
2629         }
2630
2631         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2632         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2633             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2634                 fmt::Pointer::fmt(&(*self as *const ()), f)
2635             }
2636         }
2637     }
2638 }
2639
2640 macro_rules! fnptr_impls_args {
2641     ($($Arg: ident),+) => {
2642         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2643         fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2644         fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2645         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2646         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2647         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2648     };
2649     () => {
2650         // No variadic functions with 0 parameters
2651         fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2652         fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2653         fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2654         fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2655     };
2656 }
2657
2658 fnptr_impls_args! { }
2659 fnptr_impls_args! { A }
2660 fnptr_impls_args! { A, B }
2661 fnptr_impls_args! { A, B, C }
2662 fnptr_impls_args! { A, B, C, D }
2663 fnptr_impls_args! { A, B, C, D, E }
2664 fnptr_impls_args! { A, B, C, D, E, F }
2665 fnptr_impls_args! { A, B, C, D, E, F, G }
2666 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2667 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2668 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2669 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2670 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2671
2672 // Comparison for pointers
2673 #[stable(feature = "rust1", since = "1.0.0")]
2674 impl<T: ?Sized> Ord for *const T {
2675     #[inline]
2676     fn cmp(&self, other: &*const T) -> Ordering {
2677         if self < other {
2678             Less
2679         } else if self == other {
2680             Equal
2681         } else {
2682             Greater
2683         }
2684     }
2685 }
2686
2687 #[stable(feature = "rust1", since = "1.0.0")]
2688 impl<T: ?Sized> PartialOrd for *const T {
2689     #[inline]
2690     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2691         Some(self.cmp(other))
2692     }
2693
2694     #[inline]
2695     fn lt(&self, other: &*const T) -> bool { *self < *other }
2696
2697     #[inline]
2698     fn le(&self, other: &*const T) -> bool { *self <= *other }
2699
2700     #[inline]
2701     fn gt(&self, other: &*const T) -> bool { *self > *other }
2702
2703     #[inline]
2704     fn ge(&self, other: &*const T) -> bool { *self >= *other }
2705 }
2706
2707 #[stable(feature = "rust1", since = "1.0.0")]
2708 impl<T: ?Sized> Ord for *mut T {
2709     #[inline]
2710     fn cmp(&self, other: &*mut T) -> Ordering {
2711         if self < other {
2712             Less
2713         } else if self == other {
2714             Equal
2715         } else {
2716             Greater
2717         }
2718     }
2719 }
2720
2721 #[stable(feature = "rust1", since = "1.0.0")]
2722 impl<T: ?Sized> PartialOrd for *mut T {
2723     #[inline]
2724     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2725         Some(self.cmp(other))
2726     }
2727
2728     #[inline]
2729     fn lt(&self, other: &*mut T) -> bool { *self < *other }
2730
2731     #[inline]
2732     fn le(&self, other: &*mut T) -> bool { *self <= *other }
2733
2734     #[inline]
2735     fn gt(&self, other: &*mut T) -> bool { *self > *other }
2736
2737     #[inline]
2738     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
2739 }
2740
2741 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
2742 /// of this wrapper owns the referent. Useful for building abstractions like
2743 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
2744 ///
2745 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
2746 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
2747 /// the kind of strong aliasing guarantees an instance of `T` can expect:
2748 /// the referent of the pointer should not be modified without a unique path to
2749 /// its owning Unique.
2750 ///
2751 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
2752 /// consider using `NonNull`, which has weaker semantics.
2753 ///
2754 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2755 /// is never dereferenced. This is so that enums may use this forbidden value
2756 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
2757 /// However the pointer may still dangle if it isn't dereferenced.
2758 ///
2759 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
2760 /// for any type which upholds Unique's aliasing requirements.
2761 #[unstable(feature = "ptr_internals", issue = "0",
2762            reason = "use NonNull instead and consider PhantomData<T> \
2763                      (if you also use #[may_dangle]), Send, and/or Sync")]
2764 #[doc(hidden)]
2765 #[repr(transparent)]
2766 #[rustc_layout_scalar_valid_range_start(1)]
2767 pub struct Unique<T: ?Sized> {
2768     pointer: *const T,
2769     // NOTE: this marker has no consequences for variance, but is necessary
2770     // for dropck to understand that we logically own a `T`.
2771     //
2772     // For details, see:
2773     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
2774     _marker: PhantomData<T>,
2775 }
2776
2777 #[unstable(feature = "ptr_internals", issue = "0")]
2778 impl<T: ?Sized> fmt::Debug for Unique<T> {
2779     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2780         fmt::Pointer::fmt(&self.as_ptr(), f)
2781     }
2782 }
2783
2784 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
2785 /// reference is unaliased. Note that this aliasing invariant is
2786 /// unenforced by the type system; the abstraction using the
2787 /// `Unique` must enforce it.
2788 #[unstable(feature = "ptr_internals", issue = "0")]
2789 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
2790
2791 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
2792 /// reference is unaliased. Note that this aliasing invariant is
2793 /// unenforced by the type system; the abstraction using the
2794 /// `Unique` must enforce it.
2795 #[unstable(feature = "ptr_internals", issue = "0")]
2796 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
2797
2798 #[unstable(feature = "ptr_internals", issue = "0")]
2799 impl<T: Sized> Unique<T> {
2800     /// Creates a new `Unique` that is dangling, but well-aligned.
2801     ///
2802     /// This is useful for initializing types which lazily allocate, like
2803     /// `Vec::new` does.
2804     ///
2805     /// Note that the pointer value may potentially represent a valid pointer to
2806     /// a `T`, which means this must not be used as a "not yet initialized"
2807     /// sentinel value. Types that lazily allocate must track initialization by
2808     /// some other means.
2809     // FIXME: rename to dangling() to match NonNull?
2810     pub const fn empty() -> Self {
2811         unsafe {
2812             Unique::new_unchecked(mem::align_of::<T>() as *mut T)
2813         }
2814     }
2815 }
2816
2817 #[unstable(feature = "ptr_internals", issue = "0")]
2818 impl<T: ?Sized> Unique<T> {
2819     /// Creates a new `Unique`.
2820     ///
2821     /// # Safety
2822     ///
2823     /// `ptr` must be non-null.
2824     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2825         Unique { pointer: ptr as _, _marker: PhantomData }
2826     }
2827
2828     /// Creates a new `Unique` if `ptr` is non-null.
2829     pub fn new(ptr: *mut T) -> Option<Self> {
2830         if !ptr.is_null() {
2831             Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
2832         } else {
2833             None
2834         }
2835     }
2836
2837     /// Acquires the underlying `*mut` pointer.
2838     pub const fn as_ptr(self) -> *mut T {
2839         self.pointer as *mut T
2840     }
2841
2842     /// Dereferences the content.
2843     ///
2844     /// The resulting lifetime is bound to self so this behaves "as if"
2845     /// it were actually an instance of T that is getting borrowed. If a longer
2846     /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2847     pub unsafe fn as_ref(&self) -> &T {
2848         &*self.as_ptr()
2849     }
2850
2851     /// Mutably dereferences the content.
2852     ///
2853     /// The resulting lifetime is bound to self so this behaves "as if"
2854     /// it were actually an instance of T that is getting borrowed. If a longer
2855     /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2856     pub unsafe fn as_mut(&mut self) -> &mut T {
2857         &mut *self.as_ptr()
2858     }
2859 }
2860
2861 #[unstable(feature = "ptr_internals", issue = "0")]
2862 impl<T: ?Sized> Clone for Unique<T> {
2863     fn clone(&self) -> Self {
2864         *self
2865     }
2866 }
2867
2868 #[unstable(feature = "ptr_internals", issue = "0")]
2869 impl<T: ?Sized> Copy for Unique<T> { }
2870
2871 #[unstable(feature = "ptr_internals", issue = "0")]
2872 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
2873
2874 #[unstable(feature = "ptr_internals", issue = "0")]
2875 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> { }
2876
2877 #[unstable(feature = "ptr_internals", issue = "0")]
2878 impl<T: ?Sized> fmt::Pointer for Unique<T> {
2879     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2880         fmt::Pointer::fmt(&self.as_ptr(), f)
2881     }
2882 }
2883
2884 #[unstable(feature = "ptr_internals", issue = "0")]
2885 impl<T: ?Sized> From<&mut T> for Unique<T> {
2886     fn from(reference: &mut T) -> Self {
2887         unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
2888     }
2889 }
2890
2891 #[unstable(feature = "ptr_internals", issue = "0")]
2892 impl<T: ?Sized> From<&T> for Unique<T> {
2893     fn from(reference: &T) -> Self {
2894         unsafe { Unique { pointer: reference as *const T, _marker: PhantomData } }
2895     }
2896 }
2897
2898 #[unstable(feature = "ptr_internals", issue = "0")]
2899 impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
2900     fn from(p: NonNull<T>) -> Self {
2901         unsafe { Unique { pointer: p.pointer, _marker: PhantomData } }
2902     }
2903 }
2904
2905 /// `*mut T` but non-zero and covariant.
2906 ///
2907 /// This is often the correct thing to use when building data structures using
2908 /// raw pointers, but is ultimately more dangerous to use because of its additional
2909 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
2910 ///
2911 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2912 /// is never dereferenced. This is so that enums may use this forbidden value
2913 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
2914 /// However the pointer may still dangle if it isn't dereferenced.
2915 ///
2916 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
2917 /// for your use case, you should include some [`PhantomData`] in your type to
2918 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
2919 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
2920 /// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they
2921 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
2922 ///
2923 /// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
2924 /// not change the fact that mutating through a (pointer derived from a) shared
2925 /// reference is undefined behavior unless the mutation happens inside an
2926 /// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
2927 /// reference. When using this `From` instance without an `UnsafeCell<T>`,
2928 /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
2929 /// is never used for mutation.
2930 ///
2931 /// [`PhantomData`]: ../marker/struct.PhantomData.html
2932 /// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
2933 #[stable(feature = "nonnull", since = "1.25.0")]
2934 #[repr(transparent)]
2935 #[rustc_layout_scalar_valid_range_start(1)]
2936 pub struct NonNull<T: ?Sized> {
2937     pointer: *const T,
2938 }
2939
2940 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
2941 // N.B., this impl is unnecessary, but should provide better error messages.
2942 #[stable(feature = "nonnull", since = "1.25.0")]
2943 impl<T: ?Sized> !Send for NonNull<T> { }
2944
2945 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
2946 // N.B., this impl is unnecessary, but should provide better error messages.
2947 #[stable(feature = "nonnull", since = "1.25.0")]
2948 impl<T: ?Sized> !Sync for NonNull<T> { }
2949
2950 impl<T: Sized> NonNull<T> {
2951     /// Creates a new `NonNull` that is dangling, but well-aligned.
2952     ///
2953     /// This is useful for initializing types which lazily allocate, like
2954     /// `Vec::new` does.
2955     ///
2956     /// Note that the pointer value may potentially represent a valid pointer to
2957     /// a `T`, which means this must not be used as a "not yet initialized"
2958     /// sentinel value. Types that lazily allocate must track initialization by
2959     /// some other means.
2960     #[stable(feature = "nonnull", since = "1.25.0")]
2961     #[inline]
2962     #[rustc_const_unstable(feature = "const_ptr_nonnull")]
2963     pub const fn dangling() -> Self {
2964         unsafe {
2965             let ptr = mem::align_of::<T>() as *mut T;
2966             NonNull::new_unchecked(ptr)
2967         }
2968     }
2969 }
2970
2971 impl<T: ?Sized> NonNull<T> {
2972     /// Creates a new `NonNull`.
2973     ///
2974     /// # Safety
2975     ///
2976     /// `ptr` must be non-null.
2977     #[stable(feature = "nonnull", since = "1.25.0")]
2978     #[inline]
2979     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2980         NonNull { pointer: ptr as _ }
2981     }
2982
2983     /// Creates a new `NonNull` if `ptr` is non-null.
2984     #[stable(feature = "nonnull", since = "1.25.0")]
2985     #[inline]
2986     pub fn new(ptr: *mut T) -> Option<Self> {
2987         if !ptr.is_null() {
2988             Some(unsafe { Self::new_unchecked(ptr) })
2989         } else {
2990             None
2991         }
2992     }
2993
2994     /// Acquires the underlying `*mut` pointer.
2995     #[stable(feature = "nonnull", since = "1.25.0")]
2996     #[inline]
2997     pub const fn as_ptr(self) -> *mut T {
2998         self.pointer as *mut T
2999     }
3000
3001     /// Dereferences the content.
3002     ///
3003     /// The resulting lifetime is bound to self so this behaves "as if"
3004     /// it were actually an instance of T that is getting borrowed. If a longer
3005     /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
3006     #[stable(feature = "nonnull", since = "1.25.0")]
3007     #[inline]
3008     pub unsafe fn as_ref(&self) -> &T {
3009         &*self.as_ptr()
3010     }
3011
3012     /// Mutably dereferences the content.
3013     ///
3014     /// The resulting lifetime is bound to self so this behaves "as if"
3015     /// it were actually an instance of T that is getting borrowed. If a longer
3016     /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
3017     #[stable(feature = "nonnull", since = "1.25.0")]
3018     #[inline]
3019     pub unsafe fn as_mut(&mut self) -> &mut T {
3020         &mut *self.as_ptr()
3021     }
3022
3023     /// Cast to a pointer of another type
3024     #[stable(feature = "nonnull_cast", since = "1.27.0")]
3025     #[inline]
3026     #[rustc_const_unstable(feature = "const_ptr_nonnull")]
3027     pub const fn cast<U>(self) -> NonNull<U> {
3028         unsafe {
3029             NonNull::new_unchecked(self.as_ptr() as *mut U)
3030         }
3031     }
3032 }
3033
3034 #[stable(feature = "nonnull", since = "1.25.0")]
3035 impl<T: ?Sized> Clone for NonNull<T> {
3036     fn clone(&self) -> Self {
3037         *self
3038     }
3039 }
3040
3041 #[stable(feature = "nonnull", since = "1.25.0")]
3042 impl<T: ?Sized> Copy for NonNull<T> { }
3043
3044 #[unstable(feature = "coerce_unsized", issue = "27732")]
3045 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
3046
3047 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
3048 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
3049
3050 #[stable(feature = "nonnull", since = "1.25.0")]
3051 impl<T: ?Sized> fmt::Debug for NonNull<T> {
3052     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3053         fmt::Pointer::fmt(&self.as_ptr(), f)
3054     }
3055 }
3056
3057 #[stable(feature = "nonnull", since = "1.25.0")]
3058 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
3059     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3060         fmt::Pointer::fmt(&self.as_ptr(), f)
3061     }
3062 }
3063
3064 #[stable(feature = "nonnull", since = "1.25.0")]
3065 impl<T: ?Sized> Eq for NonNull<T> {}
3066
3067 #[stable(feature = "nonnull", since = "1.25.0")]
3068 impl<T: ?Sized> PartialEq for NonNull<T> {
3069     #[inline]
3070     fn eq(&self, other: &Self) -> bool {
3071         self.as_ptr() == other.as_ptr()
3072     }
3073 }
3074
3075 #[stable(feature = "nonnull", since = "1.25.0")]
3076 impl<T: ?Sized> Ord for NonNull<T> {
3077     #[inline]
3078     fn cmp(&self, other: &Self) -> Ordering {
3079         self.as_ptr().cmp(&other.as_ptr())
3080     }
3081 }
3082
3083 #[stable(feature = "nonnull", since = "1.25.0")]
3084 impl<T: ?Sized> PartialOrd for NonNull<T> {
3085     #[inline]
3086     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3087         self.as_ptr().partial_cmp(&other.as_ptr())
3088     }
3089 }
3090
3091 #[stable(feature = "nonnull", since = "1.25.0")]
3092 impl<T: ?Sized> hash::Hash for NonNull<T> {
3093     #[inline]
3094     fn hash<H: hash::Hasher>(&self, state: &mut H) {
3095         self.as_ptr().hash(state)
3096     }
3097 }
3098
3099 #[unstable(feature = "ptr_internals", issue = "0")]
3100 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
3101     #[inline]
3102     fn from(unique: Unique<T>) -> Self {
3103         unsafe { NonNull { pointer: unique.pointer } }
3104     }
3105 }
3106
3107 #[stable(feature = "nonnull", since = "1.25.0")]
3108 impl<T: ?Sized> From<&mut T> for NonNull<T> {
3109     #[inline]
3110     fn from(reference: &mut T) -> Self {
3111         unsafe { NonNull { pointer: reference as *mut T } }
3112     }
3113 }
3114
3115 #[stable(feature = "nonnull", since = "1.25.0")]
3116 impl<T: ?Sized> From<&T> for NonNull<T> {
3117     #[inline]
3118     fn from(reference: &T) -> Self {
3119         unsafe { NonNull { pointer: reference as *const T } }
3120     }
3121 }