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