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