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