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