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