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