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