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