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