]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
Stop using deprecated NonZero APIs
[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 //! Raw, unsafe pointers, `*const T`, and `*mut T`.
14 //!
15 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
16
17 #![stable(feature = "rust1", since = "1.0.0")]
18
19 use convert::From;
20 use intrinsics;
21 use ops::CoerceUnsized;
22 use fmt;
23 use hash;
24 use marker::{PhantomData, Unsize};
25 use mem;
26 #[allow(deprecated)] use nonzero::NonZero;
27
28 use cmp::Ordering::{self, Less, Equal, Greater};
29
30 #[stable(feature = "rust1", since = "1.0.0")]
31 pub use intrinsics::copy_nonoverlapping;
32
33 #[stable(feature = "rust1", since = "1.0.0")]
34 pub use intrinsics::copy;
35
36 #[stable(feature = "rust1", since = "1.0.0")]
37 pub use intrinsics::write_bytes;
38
39 /// Executes the destructor (if any) of the pointed-to value.
40 ///
41 /// This has two use cases:
42 ///
43 /// * It is *required* to use `drop_in_place` to drop unsized types like
44 ///   trait objects, because they can't be read out onto the stack and
45 ///   dropped normally.
46 ///
47 /// * It is friendlier to the optimizer to do this over `ptr::read` when
48 ///   dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
49 ///   as the compiler doesn't need to prove that it's sound to elide the
50 ///   copy.
51 ///
52 /// # Safety
53 ///
54 /// This has all the same safety problems as `ptr::read` with respect to
55 /// invalid pointers, types, and double drops.
56 #[stable(feature = "drop_in_place", since = "1.8.0")]
57 #[lang = "drop_in_place"]
58 #[allow(unconditional_recursion)]
59 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
60     // Code here does not matter - this is replaced by the
61     // real drop glue by the compiler.
62     drop_in_place(to_drop);
63 }
64
65 /// Creates a null raw pointer.
66 ///
67 /// # Examples
68 ///
69 /// ```
70 /// use std::ptr;
71 ///
72 /// let p: *const i32 = ptr::null();
73 /// assert!(p.is_null());
74 /// ```
75 #[inline]
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub const fn null<T>() -> *const T { 0 as *const T }
78
79 /// Creates a null mutable raw pointer.
80 ///
81 /// # Examples
82 ///
83 /// ```
84 /// use std::ptr;
85 ///
86 /// let p: *mut i32 = ptr::null_mut();
87 /// assert!(p.is_null());
88 /// ```
89 #[inline]
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
92
93 /// Swaps the values at two mutable locations of the same type, without
94 /// deinitializing either.
95 ///
96 /// The values pointed at by `x` and `y` may overlap, unlike `mem::swap` which
97 /// is otherwise equivalent. If the values do overlap, then the overlapping
98 /// region of memory from `x` will be used. This is demonstrated in the
99 /// examples section below.
100 ///
101 /// # Safety
102 ///
103 /// This function copies the memory through the raw pointers passed to it
104 /// as arguments.
105 ///
106 /// Ensure that these pointers are valid before calling `swap`.
107 ///
108 /// # Examples
109 ///
110 /// Swapping two non-overlapping regions:
111 ///
112 /// ```
113 /// use std::ptr;
114 ///
115 /// let mut array = [0, 1, 2, 3];
116 ///
117 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2];
118 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2];
119 ///
120 /// unsafe {
121 ///     ptr::swap(x, y);
122 ///     assert_eq!([2, 3, 0, 1], array);
123 /// }
124 /// ```
125 ///
126 /// Swapping two overlapping regions:
127 ///
128 /// ```
129 /// use std::ptr;
130 ///
131 /// let mut array = [0, 1, 2, 3];
132 ///
133 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3];
134 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3];
135 ///
136 /// unsafe {
137 ///     ptr::swap(x, y);
138 ///     assert_eq!([1, 0, 1, 2], array);
139 /// }
140 /// ```
141 #[inline]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
144     // Give ourselves some scratch space to work with
145     let mut tmp: T = mem::uninitialized();
146
147     // Perform the swap
148     copy_nonoverlapping(x, &mut tmp, 1);
149     copy(y, x, 1); // `x` and `y` may overlap
150     copy_nonoverlapping(&tmp, y, 1);
151
152     // y and t now point to the same thing, but we need to completely forget `tmp`
153     // because it's no longer relevant.
154     mem::forget(tmp);
155 }
156
157 /// Swaps a sequence of values at two mutable locations of the same type.
158 ///
159 /// # Safety
160 ///
161 /// The two arguments must each point to the beginning of `count` locations
162 /// of valid memory, and the two memory ranges must not overlap.
163 ///
164 /// # Examples
165 ///
166 /// Basic usage:
167 ///
168 /// ```
169 /// #![feature(swap_nonoverlapping)]
170 ///
171 /// use std::ptr;
172 ///
173 /// let mut x = [1, 2, 3, 4];
174 /// let mut y = [7, 8, 9];
175 ///
176 /// unsafe {
177 ///     ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
178 /// }
179 ///
180 /// assert_eq!(x, [7, 8, 3, 4]);
181 /// assert_eq!(y, [1, 2, 9]);
182 /// ```
183 #[inline]
184 #[unstable(feature = "swap_nonoverlapping", issue = "42818")]
185 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
186     let x = x as *mut u8;
187     let y = y as *mut u8;
188     let len = mem::size_of::<T>() * count;
189     swap_nonoverlapping_bytes(x, y, len)
190 }
191
192 #[inline]
193 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
194     // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
195     // that swapping either 32 bytes or 64 bytes at a time is most efficient for intel
196     // Haswell E processors. LLVM is more able to optimize if we give a struct a
197     // #[repr(simd)], even if we don't actually use this struct directly.
198     //
199     // FIXME repr(simd) broken on emscripten and redox
200     // It's also broken on big-endian powerpc64 and s390x.  #42778
201     #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox",
202                        target_endian = "big")),
203                repr(simd))]
204     struct Block(u64, u64, u64, u64);
205     struct UnalignedBlock(u64, u64, u64, u64);
206
207     let block_size = mem::size_of::<Block>();
208
209     // Loop through x & y, copying them `Block` at a time
210     // The optimizer should unroll the loop fully for most types
211     // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
212     let mut i = 0;
213     while i + block_size <= len {
214         // Create some uninitialized memory as scratch space
215         // Declaring `t` here avoids aligning the stack when this loop is unused
216         let mut t: Block = mem::uninitialized();
217         let t = &mut t as *mut _ as *mut u8;
218         let x = x.offset(i as isize);
219         let y = y.offset(i as isize);
220
221         // Swap a block of bytes of x & y, using t as a temporary buffer
222         // This should be optimized into efficient SIMD operations where available
223         copy_nonoverlapping(x, t, block_size);
224         copy_nonoverlapping(y, x, block_size);
225         copy_nonoverlapping(t, y, block_size);
226         i += block_size;
227     }
228
229     if i < len {
230         // Swap any remaining bytes
231         let mut t: UnalignedBlock = mem::uninitialized();
232         let rem = len - i;
233
234         let t = &mut t as *mut _ as *mut u8;
235         let x = x.offset(i as isize);
236         let y = y.offset(i as isize);
237
238         copy_nonoverlapping(x, t, rem);
239         copy_nonoverlapping(y, x, rem);
240         copy_nonoverlapping(t, y, rem);
241     }
242 }
243
244 /// Replaces the value at `dest` with `src`, returning the old
245 /// value, without dropping either.
246 ///
247 /// # Safety
248 ///
249 /// This is only unsafe because it accepts a raw pointer.
250 /// Otherwise, this operation is identical to `mem::replace`.
251 #[inline]
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
254     mem::swap(&mut *dest, &mut src); // cannot overlap
255     src
256 }
257
258 /// Reads the value from `src` without moving it. This leaves the
259 /// memory in `src` unchanged.
260 ///
261 /// # Safety
262 ///
263 /// Beyond accepting a raw pointer, this is unsafe because it semantically
264 /// moves the value out of `src` without preventing further usage of `src`.
265 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
266 /// `src` is not used before the data is overwritten again (e.g. with `write`,
267 /// `write_bytes`, or `copy`). Note that `*src = foo` counts as a use
268 /// because it will attempt to drop the value previously at `*src`.
269 ///
270 /// The pointer must be aligned; use `read_unaligned` if that is not the case.
271 ///
272 /// # Examples
273 ///
274 /// Basic usage:
275 ///
276 /// ```
277 /// let x = 12;
278 /// let y = &x as *const i32;
279 ///
280 /// unsafe {
281 ///     assert_eq!(std::ptr::read(y), 12);
282 /// }
283 /// ```
284 #[inline]
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub unsafe fn read<T>(src: *const T) -> T {
287     let mut tmp: T = mem::uninitialized();
288     copy_nonoverlapping(src, &mut tmp, 1);
289     tmp
290 }
291
292 /// Reads the value from `src` without moving it. This leaves the
293 /// memory in `src` unchanged.
294 ///
295 /// Unlike `read`, the pointer may be unaligned.
296 ///
297 /// # Safety
298 ///
299 /// Beyond accepting a raw pointer, this is unsafe because it semantically
300 /// moves the value out of `src` without preventing further usage of `src`.
301 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
302 /// `src` is not used before the data is overwritten again (e.g. with `write`,
303 /// `write_bytes`, or `copy`). Note that `*src = foo` counts as a use
304 /// because it will attempt to drop the value previously at `*src`.
305 ///
306 /// # Examples
307 ///
308 /// Basic usage:
309 ///
310 /// ```
311 /// let x = 12;
312 /// let y = &x as *const i32;
313 ///
314 /// unsafe {
315 ///     assert_eq!(std::ptr::read_unaligned(y), 12);
316 /// }
317 /// ```
318 #[inline]
319 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
320 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
321     let mut tmp: T = mem::uninitialized();
322     copy_nonoverlapping(src as *const u8,
323                         &mut tmp as *mut T as *mut u8,
324                         mem::size_of::<T>());
325     tmp
326 }
327
328 /// Overwrites a memory location with the given value without reading or
329 /// dropping the old value.
330 ///
331 /// # Safety
332 ///
333 /// This operation is marked unsafe because it accepts a raw pointer.
334 ///
335 /// It does not drop the contents of `dst`. This is safe, but it could leak
336 /// allocations or resources, so care must be taken not to overwrite an object
337 /// that should be dropped.
338 ///
339 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
340 /// location pointed to by `dst`.
341 ///
342 /// This is appropriate for initializing uninitialized memory, or overwriting
343 /// memory that has previously been `read` from.
344 ///
345 /// The pointer must be aligned; use `write_unaligned` if that is not the case.
346 ///
347 /// # Examples
348 ///
349 /// Basic usage:
350 ///
351 /// ```
352 /// let mut x = 0;
353 /// let y = &mut x as *mut i32;
354 /// let z = 12;
355 ///
356 /// unsafe {
357 ///     std::ptr::write(y, z);
358 ///     assert_eq!(std::ptr::read(y), 12);
359 /// }
360 /// ```
361 #[inline]
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub unsafe fn write<T>(dst: *mut T, src: T) {
364     intrinsics::move_val_init(&mut *dst, src)
365 }
366
367 /// Overwrites a memory location with the given value without reading or
368 /// dropping the old value.
369 ///
370 /// Unlike `write`, the pointer may be unaligned.
371 ///
372 /// # Safety
373 ///
374 /// This operation is marked unsafe because it accepts a raw pointer.
375 ///
376 /// It does not drop the contents of `dst`. This is safe, but it could leak
377 /// allocations or resources, so care must be taken not to overwrite an object
378 /// that should be dropped.
379 ///
380 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
381 /// location pointed to by `dst`.
382 ///
383 /// This is appropriate for initializing uninitialized memory, or overwriting
384 /// memory that has previously been `read` from.
385 ///
386 /// # Examples
387 ///
388 /// Basic usage:
389 ///
390 /// ```
391 /// let mut x = 0;
392 /// let y = &mut x as *mut i32;
393 /// let z = 12;
394 ///
395 /// unsafe {
396 ///     std::ptr::write_unaligned(y, z);
397 ///     assert_eq!(std::ptr::read_unaligned(y), 12);
398 /// }
399 /// ```
400 #[inline]
401 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
402 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
403     copy_nonoverlapping(&src as *const T as *const u8,
404                         dst as *mut u8,
405                         mem::size_of::<T>());
406     mem::forget(src);
407 }
408
409 /// Performs a volatile read of the value from `src` without moving it. This
410 /// leaves the memory in `src` unchanged.
411 ///
412 /// Volatile operations are intended to act on I/O memory, and are guaranteed
413 /// to not be elided or reordered by the compiler across other volatile
414 /// operations.
415 ///
416 /// # Notes
417 ///
418 /// Rust does not currently have a rigorously and formally defined memory model,
419 /// so the precise semantics of what "volatile" means here is subject to change
420 /// over time. That being said, the semantics will almost always end up pretty
421 /// similar to [C11's definition of volatile][c11].
422 ///
423 /// The compiler shouldn't change the relative order or number of volatile
424 /// memory operations. However, volatile memory operations on zero-sized types
425 /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
426 /// and may be ignored.
427 ///
428 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
429 ///
430 /// # Safety
431 ///
432 /// Beyond accepting a raw pointer, this is unsafe because it semantically
433 /// moves the value out of `src` without preventing further usage of `src`.
434 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
435 /// `src` is not used before the data is overwritten again (e.g. with `write`,
436 /// `write_bytes`, or `copy`). Note that `*src = foo` counts as a use
437 /// because it will attempt to drop the value previously at `*src`.
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_volatile(y), 12);
449 /// }
450 /// ```
451 #[inline]
452 #[stable(feature = "volatile", since = "1.9.0")]
453 pub unsafe fn read_volatile<T>(src: *const T) -> T {
454     intrinsics::volatile_load(src)
455 }
456
457 /// Performs a volatile write of a memory location with the given value without
458 /// reading or dropping the old value.
459 ///
460 /// Volatile operations are intended to act on I/O memory, and are guaranteed
461 /// to not be elided or reordered by the compiler across other volatile
462 /// operations.
463 ///
464 /// # Notes
465 ///
466 /// Rust does not currently have a rigorously and formally defined memory model,
467 /// so the precise semantics of what "volatile" means here is subject to change
468 /// over time. That being said, the semantics will almost always end up pretty
469 /// similar to [C11's definition of volatile][c11].
470 ///
471 /// The compiler shouldn't change the relative order or number of volatile
472 /// memory operations. However, volatile memory operations on zero-sized types
473 /// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops
474 /// and may be ignored.
475 ///
476 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
477 ///
478 /// # Safety
479 ///
480 /// This operation is marked unsafe because it accepts a raw pointer.
481 ///
482 /// It does not drop the contents of `dst`. This is safe, but it could leak
483 /// allocations or resources, so care must be taken not to overwrite an object
484 /// that should be dropped.
485 ///
486 /// This is appropriate for initializing uninitialized memory, or overwriting
487 /// memory that has previously been `read` from.
488 ///
489 /// # Examples
490 ///
491 /// Basic usage:
492 ///
493 /// ```
494 /// let mut x = 0;
495 /// let y = &mut x as *mut i32;
496 /// let z = 12;
497 ///
498 /// unsafe {
499 ///     std::ptr::write_volatile(y, z);
500 ///     assert_eq!(std::ptr::read_volatile(y), 12);
501 /// }
502 /// ```
503 #[inline]
504 #[stable(feature = "volatile", since = "1.9.0")]
505 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
506     intrinsics::volatile_store(dst, src);
507 }
508
509 #[lang = "const_ptr"]
510 impl<T: ?Sized> *const T {
511     /// Returns `true` if the pointer is null.
512     ///
513     /// Note that unsized types have many possible null pointers, as only the
514     /// raw data pointer is considered, not their length, vtable, etc.
515     /// Therefore, two pointers that are null may still not compare equal to
516     /// each other.
517     ///
518     /// # Examples
519     ///
520     /// Basic usage:
521     ///
522     /// ```
523     /// let s: &str = "Follow the rabbit";
524     /// let ptr: *const u8 = s.as_ptr();
525     /// assert!(!ptr.is_null());
526     /// ```
527     #[stable(feature = "rust1", since = "1.0.0")]
528     #[inline]
529     pub fn is_null(self) -> bool {
530         // Compare via a cast to a thin pointer, so fat pointers are only
531         // considering their "data" part for null-ness.
532         (self as *const u8) == null()
533     }
534
535     /// Returns `None` if the pointer is null, or else returns a reference to
536     /// the value wrapped in `Some`.
537     ///
538     /// # Safety
539     ///
540     /// While this method and its mutable counterpart are useful for
541     /// null-safety, it is important to note that this is still an unsafe
542     /// operation because the returned value could be pointing to invalid
543     /// memory.
544     ///
545     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
546     /// not necessarily reflect the actual lifetime of the data.
547     ///
548     /// # Examples
549     ///
550     /// Basic usage:
551     ///
552     /// ```
553     /// let ptr: *const u8 = &10u8 as *const u8;
554     ///
555     /// unsafe {
556     ///     if let Some(val_back) = ptr.as_ref() {
557     ///         println!("We got back the value: {}!", val_back);
558     ///     }
559     /// }
560     /// ```
561     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
562     #[inline]
563     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
564         if self.is_null() {
565             None
566         } else {
567             Some(&*self)
568         }
569     }
570
571     /// Calculates the offset from a pointer.
572     ///
573     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
574     /// offset of `3 * size_of::<T>()` bytes.
575     ///
576     /// # Safety
577     ///
578     /// If any of the following conditions are violated, the result is Undefined
579     /// Behavior:
580     ///
581     /// * Both the starting and resulting pointer must be either in bounds or one
582     ///   byte past the end of an allocated object.
583     ///
584     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
585     ///
586     /// * The offset being in bounds cannot rely on "wrapping around" the address
587     ///   space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
588     ///
589     /// The compiler and standard library generally tries to ensure allocations
590     /// never reach a size where an offset is a concern. For instance, `Vec`
591     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
592     /// `vec.as_ptr().offset(vec.len() as isize)` is always safe.
593     ///
594     /// Most platforms fundamentally can't even construct such an allocation.
595     /// For instance, no known 64-bit platform can ever serve a request
596     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
597     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
598     /// more than `isize::MAX` bytes with things like Physical Address
599     /// Extension. As such, memory acquired directly from allocators or memory
600     /// mapped files *may* be too large to handle with this function.
601     ///
602     /// Consider using `wrapping_offset` instead if these constraints are
603     /// difficult to satisfy. The only advantage of this method is that it
604     /// enables more aggressive compiler optimizations.
605     ///
606     /// # Examples
607     ///
608     /// Basic usage:
609     ///
610     /// ```
611     /// let s: &str = "123";
612     /// let ptr: *const u8 = s.as_ptr();
613     ///
614     /// unsafe {
615     ///     println!("{}", *ptr.offset(1) as char);
616     ///     println!("{}", *ptr.offset(2) as char);
617     /// }
618     /// ```
619     #[stable(feature = "rust1", since = "1.0.0")]
620     #[inline]
621     pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
622         intrinsics::offset(self, count)
623     }
624
625     /// Calculates the offset from a pointer using wrapping arithmetic.
626     ///
627     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
628     /// offset of `3 * size_of::<T>()` bytes.
629     ///
630     /// # Safety
631     ///
632     /// The resulting pointer does not need to be in bounds, but it is
633     /// potentially hazardous to dereference (which requires `unsafe`).
634     ///
635     /// Always use `.offset(count)` instead when possible, because `offset`
636     /// allows the compiler to optimize better.
637     ///
638     /// # Examples
639     ///
640     /// Basic usage:
641     ///
642     /// ```
643     /// // Iterate using a raw pointer in increments of two elements
644     /// let data = [1u8, 2, 3, 4, 5];
645     /// let mut ptr: *const u8 = data.as_ptr();
646     /// let step = 2;
647     /// let end_rounded_up = ptr.wrapping_offset(6);
648     ///
649     /// // This loop prints "1, 3, 5, "
650     /// while ptr != end_rounded_up {
651     ///     unsafe {
652     ///         print!("{}, ", *ptr);
653     ///     }
654     ///     ptr = ptr.wrapping_offset(step);
655     /// }
656     /// ```
657     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
658     #[inline]
659     pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
660         unsafe {
661             intrinsics::arith_offset(self, count)
662         }
663     }
664
665     /// Calculates the distance between two pointers. The returned value is in
666     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
667     ///
668     /// If the address different between the two pointers ia not a multiple of
669     /// `mem::size_of::<T>()` then the result of the division is rounded towards
670     /// zero.
671     ///
672     /// This function returns `None` if `T` is a zero-sized typed.
673     ///
674     /// # Examples
675     ///
676     /// Basic usage:
677     ///
678     /// ```
679     /// #![feature(offset_to)]
680     ///
681     /// fn main() {
682     ///     let a = [0; 5];
683     ///     let ptr1: *const i32 = &a[1];
684     ///     let ptr2: *const i32 = &a[3];
685     ///     assert_eq!(ptr1.offset_to(ptr2), Some(2));
686     ///     assert_eq!(ptr2.offset_to(ptr1), Some(-2));
687     ///     assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
688     ///     assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
689     /// }
690     /// ```
691     #[unstable(feature = "offset_to", issue = "41079")]
692     #[inline]
693     pub fn offset_to(self, other: *const T) -> Option<isize> where T: Sized {
694         let size = mem::size_of::<T>();
695         if size == 0 {
696             None
697         } else {
698             let diff = (other as isize).wrapping_sub(self as isize);
699             Some(diff / size as isize)
700         }
701     }
702
703     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
704     ///
705     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
706     /// offset of `3 * size_of::<T>()` bytes.
707     ///
708     /// # Safety
709     ///
710     /// If any of the following conditions are violated, the result is Undefined
711     /// Behavior:
712     ///
713     /// * Both the starting and resulting pointer must be either in bounds or one
714     ///   byte past the end of an allocated object.
715     ///
716     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
717     ///
718     /// * The offset being in bounds cannot rely on "wrapping around" the address
719     ///   space. That is, the infinite-precision sum must fit in a `usize`.
720     ///
721     /// The compiler and standard library generally tries to ensure allocations
722     /// never reach a size where an offset is a concern. For instance, `Vec`
723     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
724     /// `vec.as_ptr().add(vec.len())` is always safe.
725     ///
726     /// Most platforms fundamentally can't even construct such an allocation.
727     /// For instance, no known 64-bit platform can ever serve a request
728     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
729     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
730     /// more than `isize::MAX` bytes with things like Physical Address
731     /// Extension. As such, memory acquired directly from allocators or memory
732     /// mapped files *may* be too large to handle with this function.
733     ///
734     /// Consider using `wrapping_offset` instead if these constraints are
735     /// difficult to satisfy. The only advantage of this method is that it
736     /// enables more aggressive compiler optimizations.
737     ///
738     /// # Examples
739     ///
740     /// Basic usage:
741     ///
742     /// ```
743     /// let s: &str = "123";
744     /// let ptr: *const u8 = s.as_ptr();
745     ///
746     /// unsafe {
747     ///     println!("{}", *ptr.add(1) as char);
748     ///     println!("{}", *ptr.add(2) as char);
749     /// }
750     /// ```
751     #[stable(feature = "pointer_methods", since = "1.26.0")]
752     #[inline]
753     pub unsafe fn add(self, count: usize) -> Self
754         where T: Sized,
755     {
756         self.offset(count as isize)
757     }
758
759     /// Calculates the offset from a pointer (convenience for
760     /// `.offset((count as isize).wrapping_neg())`).
761     ///
762     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
763     /// offset of `3 * size_of::<T>()` bytes.
764     ///
765     /// # Safety
766     ///
767     /// If any of the following conditions are violated, the result is Undefined
768     /// Behavior:
769     ///
770     /// * Both the starting and resulting pointer must be either in bounds or one
771     ///   byte past the end of an allocated object.
772     ///
773     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
774     ///
775     /// * The offset being in bounds cannot rely on "wrapping around" the address
776     ///   space. That is, the infinite-precision sum must fit in a usize.
777     ///
778     /// The compiler and standard library generally tries to ensure allocations
779     /// never reach a size where an offset is a concern. For instance, `Vec`
780     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
781     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
782     ///
783     /// Most platforms fundamentally can't even construct such an allocation.
784     /// For instance, no known 64-bit platform can ever serve a request
785     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
786     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
787     /// more than `isize::MAX` bytes with things like Physical Address
788     /// Extension. As such, memory acquired directly from allocators or memory
789     /// mapped files *may* be too large to handle with this function.
790     ///
791     /// Consider using `wrapping_offset` instead if these constraints are
792     /// difficult to satisfy. The only advantage of this method is that it
793     /// enables more aggressive compiler optimizations.
794     ///
795     /// # Examples
796     ///
797     /// Basic usage:
798     ///
799     /// ```
800     /// let s: &str = "123";
801     ///
802     /// unsafe {
803     ///     let end: *const u8 = s.as_ptr().add(3);
804     ///     println!("{}", *end.sub(1) as char);
805     ///     println!("{}", *end.sub(2) as char);
806     /// }
807     /// ```
808     #[stable(feature = "pointer_methods", since = "1.26.0")]
809     #[inline]
810     pub unsafe fn sub(self, count: usize) -> Self
811         where T: Sized,
812     {
813         self.offset((count as isize).wrapping_neg())
814     }
815
816     /// Calculates the offset from a pointer using wrapping arithmetic.
817     /// (convenience for `.wrapping_offset(count as isize)`)
818     ///
819     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
820     /// offset of `3 * size_of::<T>()` bytes.
821     ///
822     /// # Safety
823     ///
824     /// The resulting pointer does not need to be in bounds, but it is
825     /// potentially hazardous to dereference (which requires `unsafe`).
826     ///
827     /// Always use `.add(count)` instead when possible, because `add`
828     /// allows the compiler to optimize better.
829     ///
830     /// # Examples
831     ///
832     /// Basic usage:
833     ///
834     /// ```
835     /// // Iterate using a raw pointer in increments of two elements
836     /// let data = [1u8, 2, 3, 4, 5];
837     /// let mut ptr: *const u8 = data.as_ptr();
838     /// let step = 2;
839     /// let end_rounded_up = ptr.wrapping_add(6);
840     ///
841     /// // This loop prints "1, 3, 5, "
842     /// while ptr != end_rounded_up {
843     ///     unsafe {
844     ///         print!("{}, ", *ptr);
845     ///     }
846     ///     ptr = ptr.wrapping_add(step);
847     /// }
848     /// ```
849     #[stable(feature = "pointer_methods", since = "1.26.0")]
850     #[inline]
851     pub fn wrapping_add(self, count: usize) -> Self
852         where T: Sized,
853     {
854         self.wrapping_offset(count as isize)
855     }
856
857     /// Calculates the offset from a pointer using wrapping arithmetic.
858     /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
859     ///
860     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
861     /// offset of `3 * size_of::<T>()` bytes.
862     ///
863     /// # Safety
864     ///
865     /// The resulting pointer does not need to be in bounds, but it is
866     /// potentially hazardous to dereference (which requires `unsafe`).
867     ///
868     /// Always use `.sub(count)` instead when possible, because `sub`
869     /// allows the compiler to optimize better.
870     ///
871     /// # Examples
872     ///
873     /// Basic usage:
874     ///
875     /// ```
876     /// // Iterate using a raw pointer in increments of two elements (backwards)
877     /// let data = [1u8, 2, 3, 4, 5];
878     /// let mut ptr: *const u8 = data.as_ptr();
879     /// let start_rounded_down = ptr.wrapping_sub(2);
880     /// ptr = ptr.wrapping_add(4);
881     /// let step = 2;
882     /// // This loop prints "5, 3, 1, "
883     /// while ptr != start_rounded_down {
884     ///     unsafe {
885     ///         print!("{}, ", *ptr);
886     ///     }
887     ///     ptr = ptr.wrapping_sub(step);
888     /// }
889     /// ```
890     #[stable(feature = "pointer_methods", since = "1.26.0")]
891     #[inline]
892     pub fn wrapping_sub(self, count: usize) -> Self
893         where T: Sized,
894     {
895         self.wrapping_offset((count as isize).wrapping_neg())
896     }
897
898     /// Reads the value from `self` without moving it. This leaves the
899     /// memory in `self` unchanged.
900     ///
901     /// # Safety
902     ///
903     /// Beyond accepting a raw pointer, this is unsafe because it semantically
904     /// moves the value out of `self` without preventing further usage of `self`.
905     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
906     /// `self` is not used before the data is overwritten again (e.g. with `write`,
907     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
908     /// because it will attempt to drop the value previously at `*self`.
909     ///
910     /// The pointer must be aligned; use `read_unaligned` if that is not the case.
911     ///
912     /// # Examples
913     ///
914     /// Basic usage:
915     ///
916     /// ```
917     /// let x = 12;
918     /// let y = &x as *const i32;
919     ///
920     /// unsafe {
921     ///     assert_eq!(y.read(), 12);
922     /// }
923     /// ```
924     #[stable(feature = "pointer_methods", since = "1.26.0")]
925     #[inline]
926     pub unsafe fn read(self) -> T
927         where T: Sized,
928     {
929         read(self)
930     }
931
932     /// Performs a volatile read of the value from `self` without moving it. This
933     /// leaves the memory in `self` unchanged.
934     ///
935     /// Volatile operations are intended to act on I/O memory, and are guaranteed
936     /// to not be elided or reordered by the compiler across other volatile
937     /// operations.
938     ///
939     /// # Notes
940     ///
941     /// Rust does not currently have a rigorously and formally defined memory model,
942     /// so the precise semantics of what "volatile" means here is subject to change
943     /// over time. That being said, the semantics will almost always end up pretty
944     /// similar to [C11's definition of volatile][c11].
945     ///
946     /// The compiler shouldn't change the relative order or number of volatile
947     /// memory operations. However, volatile memory operations on zero-sized types
948     /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
949     /// and may be ignored.
950     ///
951     /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
952     ///
953     /// # Safety
954     ///
955     /// Beyond accepting a raw pointer, this is unsafe because it semantically
956     /// moves the value out of `self` without preventing further usage of `self`.
957     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
958     /// `self` is not used before the data is overwritten again (e.g. with `write`,
959     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
960     /// because it will attempt to drop the value previously at `*self`.
961     ///
962     /// # Examples
963     ///
964     /// Basic usage:
965     ///
966     /// ```
967     /// let x = 12;
968     /// let y = &x as *const i32;
969     ///
970     /// unsafe {
971     ///     assert_eq!(y.read_volatile(), 12);
972     /// }
973     /// ```
974     #[stable(feature = "pointer_methods", since = "1.26.0")]
975     #[inline]
976     pub unsafe fn read_volatile(self) -> T
977         where T: Sized,
978     {
979         read_volatile(self)
980     }
981
982     /// Reads the value from `self` without moving it. This leaves the
983     /// memory in `self` unchanged.
984     ///
985     /// Unlike `read`, the pointer may be unaligned.
986     ///
987     /// # Safety
988     ///
989     /// Beyond accepting a raw pointer, this is unsafe because it semantically
990     /// moves the value out of `self` without preventing further usage of `self`.
991     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
992     /// `self` is not used before the data is overwritten again (e.g. with `write`,
993     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
994     /// because it will attempt to drop the value previously at `*self`.
995     ///
996     /// # Examples
997     ///
998     /// Basic usage:
999     ///
1000     /// ```
1001     /// let x = 12;
1002     /// let y = &x as *const i32;
1003     ///
1004     /// unsafe {
1005     ///     assert_eq!(y.read_unaligned(), 12);
1006     /// }
1007     /// ```
1008     #[stable(feature = "pointer_methods", since = "1.26.0")]
1009     #[inline]
1010     pub unsafe fn read_unaligned(self) -> T
1011         where T: Sized,
1012     {
1013         read_unaligned(self)
1014     }
1015
1016     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1017     /// and destination may overlap.
1018     ///
1019     /// NOTE: this has the *same* argument order as `ptr::copy`.
1020     ///
1021     /// This is semantically equivalent to C's `memmove`.
1022     ///
1023     /// # Safety
1024     ///
1025     /// Care must be taken with the ownership of `self` and `dest`.
1026     /// This method semantically moves the values of `self` into `dest`.
1027     /// However it does not drop the contents of `self`, or prevent the contents
1028     /// of `dest` from being dropped or used.
1029     ///
1030     /// # Examples
1031     ///
1032     /// Efficiently create a Rust vector from an unsafe buffer:
1033     ///
1034     /// ```
1035     /// # #[allow(dead_code)]
1036     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1037     ///     let mut dst = Vec::with_capacity(elts);
1038     ///     dst.set_len(elts);
1039     ///     ptr.copy_to(dst.as_mut_ptr(), elts);
1040     ///     dst
1041     /// }
1042     /// ```
1043     #[stable(feature = "pointer_methods", since = "1.26.0")]
1044     #[inline]
1045     pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1046         where T: Sized,
1047     {
1048         copy(self, dest, count)
1049     }
1050
1051     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1052     /// and destination may *not* overlap.
1053     ///
1054     /// NOTE: this has the *same* argument order as `ptr::copy_nonoverlapping`.
1055     ///
1056     /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
1057     ///
1058     /// # Safety
1059     ///
1060     /// Beyond requiring that the program must be allowed to access both regions
1061     /// of memory, it is Undefined Behavior for source and destination to
1062     /// overlap. Care must also be taken with the ownership of `self` and
1063     /// `self`. This method semantically moves the values of `self` into `dest`.
1064     /// However it does not drop the contents of `dest`, or prevent the contents
1065     /// of `self` from being dropped or used.
1066     ///
1067     /// # Examples
1068     ///
1069     /// Efficiently create a Rust vector from an unsafe buffer:
1070     ///
1071     /// ```
1072     /// # #[allow(dead_code)]
1073     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1074     ///     let mut dst = Vec::with_capacity(elts);
1075     ///     dst.set_len(elts);
1076     ///     ptr.copy_to_nonoverlapping(dst.as_mut_ptr(), elts);
1077     ///     dst
1078     /// }
1079     /// ```
1080     #[stable(feature = "pointer_methods", since = "1.26.0")]
1081     #[inline]
1082     pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1083         where T: Sized,
1084     {
1085         copy_nonoverlapping(self, dest, count)
1086     }
1087
1088     /// Computes the byte offset that needs to be applied in order to
1089     /// make the pointer aligned to `align`.
1090     /// If it is not possible to align the pointer, the implementation returns
1091     /// `usize::max_value()`.
1092     ///
1093     /// There are no guarantees whatsover that offsetting the pointer will not
1094     /// overflow or go beyond the allocation that the pointer points into.
1095     /// It is up to the caller to ensure that the returned offset is correct
1096     /// in all terms other than alignment.
1097     ///
1098     /// # Examples
1099     ///
1100     /// Accessing adjacent `u8` as `u16`
1101     ///
1102     /// ```
1103     /// # #![feature(align_offset)]
1104     /// # fn foo(n: usize) {
1105     /// # use std::mem::align_of;
1106     /// # unsafe {
1107     /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1108     /// let ptr = &x[n] as *const u8;
1109     /// let offset = ptr.align_offset(align_of::<u16>());
1110     /// if offset < x.len() - n - 1 {
1111     ///     let u16_ptr = ptr.offset(offset as isize) as *const u16;
1112     ///     assert_ne!(*u16_ptr, 500);
1113     /// } else {
1114     ///     // while the pointer can be aligned via `offset`, it would point
1115     ///     // outside the allocation
1116     /// }
1117     /// # } }
1118     /// ```
1119     #[unstable(feature = "align_offset", issue = "44488")]
1120     pub fn align_offset(self, align: usize) -> usize {
1121         unsafe {
1122             intrinsics::align_offset(self as *const _, align)
1123         }
1124     }
1125 }
1126
1127 #[lang = "mut_ptr"]
1128 impl<T: ?Sized> *mut T {
1129     /// Returns `true` if the pointer is null.
1130     ///
1131     /// Note that unsized types have many possible null pointers, as only the
1132     /// raw data pointer is considered, not their length, vtable, etc.
1133     /// Therefore, two pointers that are null may still not compare equal to
1134     /// each other.
1135     ///
1136     /// # Examples
1137     ///
1138     /// Basic usage:
1139     ///
1140     /// ```
1141     /// let mut s = [1, 2, 3];
1142     /// let ptr: *mut u32 = s.as_mut_ptr();
1143     /// assert!(!ptr.is_null());
1144     /// ```
1145     #[stable(feature = "rust1", since = "1.0.0")]
1146     #[inline]
1147     pub fn is_null(self) -> bool {
1148         // Compare via a cast to a thin pointer, so fat pointers are only
1149         // considering their "data" part for null-ness.
1150         (self as *mut u8) == null_mut()
1151     }
1152
1153     /// Returns `None` if the pointer is null, or else returns a reference to
1154     /// the value wrapped in `Some`.
1155     ///
1156     /// # Safety
1157     ///
1158     /// While this method and its mutable counterpart are useful for
1159     /// null-safety, it is important to note that this is still an unsafe
1160     /// operation because the returned value could be pointing to invalid
1161     /// memory.
1162     ///
1163     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1164     /// not necessarily reflect the actual lifetime of the data.
1165     ///
1166     /// # Examples
1167     ///
1168     /// Basic usage:
1169     ///
1170     /// ```
1171     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1172     ///
1173     /// unsafe {
1174     ///     if let Some(val_back) = ptr.as_ref() {
1175     ///         println!("We got back the value: {}!", val_back);
1176     ///     }
1177     /// }
1178     /// ```
1179     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1180     #[inline]
1181     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1182         if self.is_null() {
1183             None
1184         } else {
1185             Some(&*self)
1186         }
1187     }
1188
1189     /// Calculates the offset from a pointer.
1190     ///
1191     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1192     /// offset of `3 * size_of::<T>()` bytes.
1193     ///
1194     /// # Safety
1195     ///
1196     /// If any of the following conditions are violated, the result is Undefined
1197     /// Behavior:
1198     ///
1199     /// * Both the starting and resulting pointer must be either in bounds or one
1200     ///   byte past the end of an allocated object.
1201     ///
1202     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1203     ///
1204     /// * The offset being in bounds cannot rely on "wrapping around" the address
1205     ///   space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1206     ///
1207     /// The compiler and standard library generally tries to ensure allocations
1208     /// never reach a size where an offset is a concern. For instance, `Vec`
1209     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1210     /// `vec.as_ptr().offset(vec.len() as isize)` is always safe.
1211     ///
1212     /// Most platforms fundamentally can't even construct such an allocation.
1213     /// For instance, no known 64-bit platform can ever serve a request
1214     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1215     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1216     /// more than `isize::MAX` bytes with things like Physical Address
1217     /// Extension. As such, memory acquired directly from allocators or memory
1218     /// mapped files *may* be too large to handle with this function.
1219     ///
1220     /// Consider using `wrapping_offset` instead if these constraints are
1221     /// difficult to satisfy. The only advantage of this method is that it
1222     /// enables more aggressive compiler optimizations.
1223     ///
1224     /// # Examples
1225     ///
1226     /// Basic usage:
1227     ///
1228     /// ```
1229     /// let mut s = [1, 2, 3];
1230     /// let ptr: *mut u32 = s.as_mut_ptr();
1231     ///
1232     /// unsafe {
1233     ///     println!("{}", *ptr.offset(1));
1234     ///     println!("{}", *ptr.offset(2));
1235     /// }
1236     /// ```
1237     #[stable(feature = "rust1", since = "1.0.0")]
1238     #[inline]
1239     pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1240         intrinsics::offset(self, count) as *mut T
1241     }
1242
1243     /// Calculates the offset from a pointer using wrapping arithmetic.
1244     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1245     /// offset of `3 * size_of::<T>()` bytes.
1246     ///
1247     /// # Safety
1248     ///
1249     /// The resulting pointer does not need to be in bounds, but it is
1250     /// potentially hazardous to dereference (which requires `unsafe`).
1251     ///
1252     /// Always use `.offset(count)` instead when possible, because `offset`
1253     /// allows the compiler to optimize better.
1254     ///
1255     /// # Examples
1256     ///
1257     /// Basic usage:
1258     ///
1259     /// ```
1260     /// // Iterate using a raw pointer in increments of two elements
1261     /// let mut data = [1u8, 2, 3, 4, 5];
1262     /// let mut ptr: *mut u8 = data.as_mut_ptr();
1263     /// let step = 2;
1264     /// let end_rounded_up = ptr.wrapping_offset(6);
1265     ///
1266     /// while ptr != end_rounded_up {
1267     ///     unsafe {
1268     ///         *ptr = 0;
1269     ///     }
1270     ///     ptr = ptr.wrapping_offset(step);
1271     /// }
1272     /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1273     /// ```
1274     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1275     #[inline]
1276     pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1277         unsafe {
1278             intrinsics::arith_offset(self, count) as *mut T
1279         }
1280     }
1281
1282     /// Returns `None` if the pointer is null, or else returns a mutable
1283     /// reference to the value wrapped in `Some`.
1284     ///
1285     /// # Safety
1286     ///
1287     /// As with `as_ref`, this is unsafe because it cannot verify the validity
1288     /// of the returned pointer, nor can it ensure that the lifetime `'a`
1289     /// returned is indeed a valid lifetime for the contained data.
1290     ///
1291     /// # Examples
1292     ///
1293     /// Basic usage:
1294     ///
1295     /// ```
1296     /// let mut s = [1, 2, 3];
1297     /// let ptr: *mut u32 = s.as_mut_ptr();
1298     /// let first_value = unsafe { ptr.as_mut().unwrap() };
1299     /// *first_value = 4;
1300     /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1301     /// ```
1302     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1303     #[inline]
1304     pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1305         if self.is_null() {
1306             None
1307         } else {
1308             Some(&mut *self)
1309         }
1310     }
1311
1312     /// Calculates the distance between two pointers. The returned value is in
1313     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1314     ///
1315     /// If the address different between the two pointers ia not a multiple of
1316     /// `mem::size_of::<T>()` then the result of the division is rounded towards
1317     /// zero.
1318     ///
1319     /// This function returns `None` if `T` is a zero-sized typed.
1320     ///
1321     /// # Examples
1322     ///
1323     /// Basic usage:
1324     ///
1325     /// ```
1326     /// #![feature(offset_to)]
1327     ///
1328     /// fn main() {
1329     ///     let mut a = [0; 5];
1330     ///     let ptr1: *mut i32 = &mut a[1];
1331     ///     let ptr2: *mut i32 = &mut a[3];
1332     ///     assert_eq!(ptr1.offset_to(ptr2), Some(2));
1333     ///     assert_eq!(ptr2.offset_to(ptr1), Some(-2));
1334     ///     assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
1335     ///     assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
1336     /// }
1337     /// ```
1338     #[unstable(feature = "offset_to", issue = "41079")]
1339     #[inline]
1340     pub fn offset_to(self, other: *const T) -> Option<isize> where T: Sized {
1341         let size = mem::size_of::<T>();
1342         if size == 0 {
1343             None
1344         } else {
1345             let diff = (other as isize).wrapping_sub(self as isize);
1346             Some(diff / size as isize)
1347         }
1348     }
1349
1350     /// Computes the byte offset that needs to be applied in order to
1351     /// make the pointer aligned to `align`.
1352     /// If it is not possible to align the pointer, the implementation returns
1353     /// `usize::max_value()`.
1354     ///
1355     /// There are no guarantees whatsover that offsetting the pointer will not
1356     /// overflow or go beyond the allocation that the pointer points into.
1357     /// It is up to the caller to ensure that the returned offset is correct
1358     /// in all terms other than alignment.
1359     ///
1360     /// # Examples
1361     ///
1362     /// Accessing adjacent `u8` as `u16`
1363     ///
1364     /// ```
1365     /// # #![feature(align_offset)]
1366     /// # fn foo(n: usize) {
1367     /// # use std::mem::align_of;
1368     /// # unsafe {
1369     /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1370     /// let ptr = &x[n] as *const u8;
1371     /// let offset = ptr.align_offset(align_of::<u16>());
1372     /// if offset < x.len() - n - 1 {
1373     ///     let u16_ptr = ptr.offset(offset as isize) as *const u16;
1374     ///     assert_ne!(*u16_ptr, 500);
1375     /// } else {
1376     ///     // while the pointer can be aligned via `offset`, it would point
1377     ///     // outside the allocation
1378     /// }
1379     /// # } }
1380     /// ```
1381     #[unstable(feature = "align_offset", issue = "44488")]
1382     pub fn align_offset(self, align: usize) -> usize {
1383         unsafe {
1384             intrinsics::align_offset(self as *const _, align)
1385         }
1386     }
1387
1388     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1389     ///
1390     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1391     /// offset of `3 * size_of::<T>()` bytes.
1392     ///
1393     /// # Safety
1394     ///
1395     /// If any of the following conditions are violated, the result is Undefined
1396     /// Behavior:
1397     ///
1398     /// * Both the starting and resulting pointer must be either in bounds or one
1399     ///   byte past the end of an allocated object.
1400     ///
1401     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1402     ///
1403     /// * The offset being in bounds cannot rely on "wrapping around" the address
1404     ///   space. That is, the infinite-precision sum must fit in a `usize`.
1405     ///
1406     /// The compiler and standard library generally tries to ensure allocations
1407     /// never reach a size where an offset is a concern. For instance, `Vec`
1408     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1409     /// `vec.as_ptr().add(vec.len())` is always safe.
1410     ///
1411     /// Most platforms fundamentally can't even construct such an allocation.
1412     /// For instance, no known 64-bit platform can ever serve a request
1413     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1414     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1415     /// more than `isize::MAX` bytes with things like Physical Address
1416     /// Extension. As such, memory acquired directly from allocators or memory
1417     /// mapped files *may* be too large to handle with this function.
1418     ///
1419     /// Consider using `wrapping_offset` instead if these constraints are
1420     /// difficult to satisfy. The only advantage of this method is that it
1421     /// enables more aggressive compiler optimizations.
1422     ///
1423     /// # Examples
1424     ///
1425     /// Basic usage:
1426     ///
1427     /// ```
1428     /// let s: &str = "123";
1429     /// let ptr: *const u8 = s.as_ptr();
1430     ///
1431     /// unsafe {
1432     ///     println!("{}", *ptr.add(1) as char);
1433     ///     println!("{}", *ptr.add(2) as char);
1434     /// }
1435     /// ```
1436     #[stable(feature = "pointer_methods", since = "1.26.0")]
1437     #[inline]
1438     pub unsafe fn add(self, count: usize) -> Self
1439         where T: Sized,
1440     {
1441         self.offset(count as isize)
1442     }
1443
1444     /// Calculates the offset from a pointer (convenience for
1445     /// `.offset((count as isize).wrapping_neg())`).
1446     ///
1447     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1448     /// offset of `3 * size_of::<T>()` bytes.
1449     ///
1450     /// # Safety
1451     ///
1452     /// If any of the following conditions are violated, the result is Undefined
1453     /// Behavior:
1454     ///
1455     /// * Both the starting and resulting pointer must be either in bounds or one
1456     ///   byte past the end of an allocated object.
1457     ///
1458     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1459     ///
1460     /// * The offset being in bounds cannot rely on "wrapping around" the address
1461     ///   space. That is, the infinite-precision sum must fit in a usize.
1462     ///
1463     /// The compiler and standard library generally tries to ensure allocations
1464     /// never reach a size where an offset is a concern. For instance, `Vec`
1465     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1466     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1467     ///
1468     /// Most platforms fundamentally can't even construct such an allocation.
1469     /// For instance, no known 64-bit platform can ever serve a request
1470     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1471     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1472     /// more than `isize::MAX` bytes with things like Physical Address
1473     /// Extension. As such, memory acquired directly from allocators or memory
1474     /// mapped files *may* be too large to handle with this function.
1475     ///
1476     /// Consider using `wrapping_offset` instead if these constraints are
1477     /// difficult to satisfy. The only advantage of this method is that it
1478     /// enables more aggressive compiler optimizations.
1479     ///
1480     /// # Examples
1481     ///
1482     /// Basic usage:
1483     ///
1484     /// ```
1485     /// let s: &str = "123";
1486     ///
1487     /// unsafe {
1488     ///     let end: *const u8 = s.as_ptr().add(3);
1489     ///     println!("{}", *end.sub(1) as char);
1490     ///     println!("{}", *end.sub(2) as char);
1491     /// }
1492     /// ```
1493     #[stable(feature = "pointer_methods", since = "1.26.0")]
1494     #[inline]
1495     pub unsafe fn sub(self, count: usize) -> Self
1496         where T: Sized,
1497     {
1498         self.offset((count as isize).wrapping_neg())
1499     }
1500
1501     /// Calculates the offset from a pointer using wrapping arithmetic.
1502     /// (convenience for `.wrapping_offset(count as isize)`)
1503     ///
1504     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1505     /// offset of `3 * size_of::<T>()` bytes.
1506     ///
1507     /// # Safety
1508     ///
1509     /// The resulting pointer does not need to be in bounds, but it is
1510     /// potentially hazardous to dereference (which requires `unsafe`).
1511     ///
1512     /// Always use `.add(count)` instead when possible, because `add`
1513     /// allows the compiler to optimize better.
1514     ///
1515     /// # Examples
1516     ///
1517     /// Basic usage:
1518     ///
1519     /// ```
1520     /// // Iterate using a raw pointer in increments of two elements
1521     /// let data = [1u8, 2, 3, 4, 5];
1522     /// let mut ptr: *const u8 = data.as_ptr();
1523     /// let step = 2;
1524     /// let end_rounded_up = ptr.wrapping_add(6);
1525     ///
1526     /// // This loop prints "1, 3, 5, "
1527     /// while ptr != end_rounded_up {
1528     ///     unsafe {
1529     ///         print!("{}, ", *ptr);
1530     ///     }
1531     ///     ptr = ptr.wrapping_add(step);
1532     /// }
1533     /// ```
1534     #[stable(feature = "pointer_methods", since = "1.26.0")]
1535     #[inline]
1536     pub fn wrapping_add(self, count: usize) -> Self
1537         where T: Sized,
1538     {
1539         self.wrapping_offset(count as isize)
1540     }
1541
1542     /// Calculates the offset from a pointer using wrapping arithmetic.
1543     /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1544     ///
1545     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1546     /// offset of `3 * size_of::<T>()` bytes.
1547     ///
1548     /// # Safety
1549     ///
1550     /// The resulting pointer does not need to be in bounds, but it is
1551     /// potentially hazardous to dereference (which requires `unsafe`).
1552     ///
1553     /// Always use `.sub(count)` instead when possible, because `sub`
1554     /// allows the compiler to optimize better.
1555     ///
1556     /// # Examples
1557     ///
1558     /// Basic usage:
1559     ///
1560     /// ```
1561     /// // Iterate using a raw pointer in increments of two elements (backwards)
1562     /// let data = [1u8, 2, 3, 4, 5];
1563     /// let mut ptr: *const u8 = data.as_ptr();
1564     /// let start_rounded_down = ptr.wrapping_sub(2);
1565     /// ptr = ptr.wrapping_add(4);
1566     /// let step = 2;
1567     /// // This loop prints "5, 3, 1, "
1568     /// while ptr != start_rounded_down {
1569     ///     unsafe {
1570     ///         print!("{}, ", *ptr);
1571     ///     }
1572     ///     ptr = ptr.wrapping_sub(step);
1573     /// }
1574     /// ```
1575     #[stable(feature = "pointer_methods", since = "1.26.0")]
1576     #[inline]
1577     pub fn wrapping_sub(self, count: usize) -> Self
1578         where T: Sized,
1579     {
1580         self.wrapping_offset((count as isize).wrapping_neg())
1581     }
1582
1583     /// Reads the value from `self` without moving it. This leaves the
1584     /// memory in `self` unchanged.
1585     ///
1586     /// # Safety
1587     ///
1588     /// Beyond accepting a raw pointer, this is unsafe because it semantically
1589     /// moves the value out of `self` without preventing further usage of `self`.
1590     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1591     /// `self` is not used before the data is overwritten again (e.g. with `write`,
1592     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1593     /// because it will attempt to drop the value previously at `*self`.
1594     ///
1595     /// The pointer must be aligned; use `read_unaligned` if that is not the case.
1596     ///
1597     /// # Examples
1598     ///
1599     /// Basic usage:
1600     ///
1601     /// ```
1602     /// let x = 12;
1603     /// let y = &x as *const i32;
1604     ///
1605     /// unsafe {
1606     ///     assert_eq!(y.read(), 12);
1607     /// }
1608     /// ```
1609     #[stable(feature = "pointer_methods", since = "1.26.0")]
1610     #[inline]
1611     pub unsafe fn read(self) -> T
1612         where T: Sized,
1613     {
1614         read(self)
1615     }
1616
1617     /// Performs a volatile read of the value from `self` without moving it. This
1618     /// leaves the memory in `self` unchanged.
1619     ///
1620     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1621     /// to not be elided or reordered by the compiler across other volatile
1622     /// operations.
1623     ///
1624     /// # Notes
1625     ///
1626     /// Rust does not currently have a rigorously and formally defined memory model,
1627     /// so the precise semantics of what "volatile" means here is subject to change
1628     /// over time. That being said, the semantics will almost always end up pretty
1629     /// similar to [C11's definition of volatile][c11].
1630     ///
1631     /// The compiler shouldn't change the relative order or number of volatile
1632     /// memory operations. However, volatile memory operations on zero-sized types
1633     /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
1634     /// and may be ignored.
1635     ///
1636     /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1637     ///
1638     /// # Safety
1639     ///
1640     /// Beyond accepting a raw pointer, this is unsafe because it semantically
1641     /// moves the value out of `self` without preventing further usage of `self`.
1642     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1643     /// `self` is not used before the data is overwritten again (e.g. with `write`,
1644     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1645     /// because it will attempt to drop the value previously at `*self`.
1646     ///
1647     /// # Examples
1648     ///
1649     /// Basic usage:
1650     ///
1651     /// ```
1652     /// let x = 12;
1653     /// let y = &x as *const i32;
1654     ///
1655     /// unsafe {
1656     ///     assert_eq!(y.read_volatile(), 12);
1657     /// }
1658     /// ```
1659     #[stable(feature = "pointer_methods", since = "1.26.0")]
1660     #[inline]
1661     pub unsafe fn read_volatile(self) -> T
1662         where T: Sized,
1663     {
1664         read_volatile(self)
1665     }
1666
1667     /// Reads the value from `self` without moving it. This leaves the
1668     /// memory in `self` unchanged.
1669     ///
1670     /// Unlike `read`, the pointer may be unaligned.
1671     ///
1672     /// # Safety
1673     ///
1674     /// Beyond accepting a raw pointer, this is unsafe because it semantically
1675     /// moves the value out of `self` without preventing further usage of `self`.
1676     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1677     /// `self` is not used before the data is overwritten again (e.g. with `write`,
1678     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1679     /// because it will attempt to drop the value previously at `*self`.
1680     ///
1681     /// # Examples
1682     ///
1683     /// Basic usage:
1684     ///
1685     /// ```
1686     /// let x = 12;
1687     /// let y = &x as *const i32;
1688     ///
1689     /// unsafe {
1690     ///     assert_eq!(y.read_unaligned(), 12);
1691     /// }
1692     /// ```
1693     #[stable(feature = "pointer_methods", since = "1.26.0")]
1694     #[inline]
1695     pub unsafe fn read_unaligned(self) -> T
1696         where T: Sized,
1697     {
1698         read_unaligned(self)
1699     }
1700
1701     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1702     /// and destination may overlap.
1703     ///
1704     /// NOTE: this has the *same* argument order as `ptr::copy`.
1705     ///
1706     /// This is semantically equivalent to C's `memmove`.
1707     ///
1708     /// # Safety
1709     ///
1710     /// Care must be taken with the ownership of `self` and `dest`.
1711     /// This method semantically moves the values of `self` into `dest`.
1712     /// However it does not drop the contents of `self`, or prevent the contents
1713     /// of `dest` from being dropped or used.
1714     ///
1715     /// # Examples
1716     ///
1717     /// Efficiently create a Rust vector from an unsafe buffer:
1718     ///
1719     /// ```
1720     /// # #[allow(dead_code)]
1721     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1722     ///     let mut dst = Vec::with_capacity(elts);
1723     ///     dst.set_len(elts);
1724     ///     ptr.copy_to(dst.as_mut_ptr(), elts);
1725     ///     dst
1726     /// }
1727     /// ```
1728     #[stable(feature = "pointer_methods", since = "1.26.0")]
1729     #[inline]
1730     pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1731         where T: Sized,
1732     {
1733         copy(self, dest, count)
1734     }
1735
1736     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1737     /// and destination may *not* overlap.
1738     ///
1739     /// NOTE: this has the *same* argument order as `ptr::copy_nonoverlapping`.
1740     ///
1741     /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
1742     ///
1743     /// # Safety
1744     ///
1745     /// Beyond requiring that the program must be allowed to access both regions
1746     /// of memory, it is Undefined Behavior for source and destination to
1747     /// overlap. Care must also be taken with the ownership of `self` and
1748     /// `self`. This method semantically moves the values of `self` into `dest`.
1749     /// However it does not drop the contents of `dest`, or prevent the contents
1750     /// of `self` from being dropped or used.
1751     ///
1752     /// # Examples
1753     ///
1754     /// Efficiently create a Rust vector from an unsafe buffer:
1755     ///
1756     /// ```
1757     /// # #[allow(dead_code)]
1758     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1759     ///     let mut dst = Vec::with_capacity(elts);
1760     ///     dst.set_len(elts);
1761     ///     ptr.copy_to_nonoverlapping(dst.as_mut_ptr(), elts);
1762     ///     dst
1763     /// }
1764     /// ```
1765     #[stable(feature = "pointer_methods", since = "1.26.0")]
1766     #[inline]
1767     pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1768         where T: Sized,
1769     {
1770         copy_nonoverlapping(self, dest, count)
1771     }
1772
1773     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1774     /// and destination may overlap.
1775     ///
1776     /// NOTE: this has the *opposite* argument order of `ptr::copy`.
1777     ///
1778     /// This is semantically equivalent to C's `memmove`.
1779     ///
1780     /// # Safety
1781     ///
1782     /// Care must be taken with the ownership of `src` and `self`.
1783     /// This method semantically moves the values of `src` into `self`.
1784     /// However it does not drop the contents of `self`, or prevent the contents
1785     /// of `src` from being dropped or used.
1786     ///
1787     /// # Examples
1788     ///
1789     /// Efficiently create a Rust vector from an unsafe buffer:
1790     ///
1791     /// ```
1792     /// # #[allow(dead_code)]
1793     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1794     ///     let mut dst: Vec<T> = Vec::with_capacity(elts);
1795     ///     dst.set_len(elts);
1796     ///     dst.as_mut_ptr().copy_from(ptr, elts);
1797     ///     dst
1798     /// }
1799     /// ```
1800     #[stable(feature = "pointer_methods", since = "1.26.0")]
1801     #[inline]
1802     pub unsafe fn copy_from(self, src: *const T, count: usize)
1803         where T: Sized,
1804     {
1805         copy(src, self, count)
1806     }
1807
1808     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1809     /// and destination may *not* overlap.
1810     ///
1811     /// NOTE: this has the *opposite* argument order of `ptr::copy_nonoverlapping`.
1812     ///
1813     /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
1814     ///
1815     /// # Safety
1816     ///
1817     /// Beyond requiring that the program must be allowed to access both regions
1818     /// of memory, it is Undefined Behavior for source and destination to
1819     /// overlap. Care must also be taken with the ownership of `src` and
1820     /// `self`. This method semantically moves the values of `src` into `self`.
1821     /// However it does not drop the contents of `self`, or prevent the contents
1822     /// of `src` from being dropped or used.
1823     ///
1824     /// # Examples
1825     ///
1826     /// Efficiently create a Rust vector from an unsafe buffer:
1827     ///
1828     /// ```
1829     /// # #[allow(dead_code)]
1830     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1831     ///     let mut dst: Vec<T> = Vec::with_capacity(elts);
1832     ///     dst.set_len(elts);
1833     ///     dst.as_mut_ptr().copy_from_nonoverlapping(ptr, elts);
1834     ///     dst
1835     /// }
1836     /// ```
1837     #[stable(feature = "pointer_methods", since = "1.26.0")]
1838     #[inline]
1839     pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1840         where T: Sized,
1841     {
1842         copy_nonoverlapping(src, self, count)
1843     }
1844
1845     /// Executes the destructor (if any) of the pointed-to value.
1846     ///
1847     /// This has two use cases:
1848     ///
1849     /// * It is *required* to use `drop_in_place` to drop unsized types like
1850     ///   trait objects, because they can't be read out onto the stack and
1851     ///   dropped normally.
1852     ///
1853     /// * It is friendlier to the optimizer to do this over `ptr::read` when
1854     ///   dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
1855     ///   as the compiler doesn't need to prove that it's sound to elide the
1856     ///   copy.
1857     ///
1858     /// # Safety
1859     ///
1860     /// This has all the same safety problems as `ptr::read` with respect to
1861     /// invalid pointers, types, and double drops.
1862     #[stable(feature = "pointer_methods", since = "1.26.0")]
1863     #[inline]
1864     pub unsafe fn drop_in_place(self) {
1865         drop_in_place(self)
1866     }
1867
1868     /// Overwrites a memory location with the given value without reading or
1869     /// dropping the old value.
1870     ///
1871     /// # Safety
1872     ///
1873     /// This operation is marked unsafe because it writes through a raw pointer.
1874     ///
1875     /// It does not drop the contents of `self`. This is safe, but it could leak
1876     /// allocations or resources, so care must be taken not to overwrite an object
1877     /// that should be dropped.
1878     ///
1879     /// Additionally, it does not drop `val`. Semantically, `val` is moved into the
1880     /// location pointed to by `self`.
1881     ///
1882     /// This is appropriate for initializing uninitialized memory, or overwriting
1883     /// memory that has previously been `read` from.
1884     ///
1885     /// The pointer must be aligned; use `write_unaligned` if that is not the case.
1886     ///
1887     /// # Examples
1888     ///
1889     /// Basic usage:
1890     ///
1891     /// ```
1892     /// let mut x = 0;
1893     /// let y = &mut x as *mut i32;
1894     /// let z = 12;
1895     ///
1896     /// unsafe {
1897     ///     y.write(z);
1898     ///     assert_eq!(y.read(), 12);
1899     /// }
1900     /// ```
1901     #[stable(feature = "pointer_methods", since = "1.26.0")]
1902     #[inline]
1903     pub unsafe fn write(self, val: T)
1904         where T: Sized,
1905     {
1906         write(self, val)
1907     }
1908
1909     /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1910     /// bytes of memory starting at `self` to `val`.
1911     ///
1912     /// # Examples
1913     ///
1914     /// ```
1915     /// let mut vec = vec![0; 4];
1916     /// unsafe {
1917     ///     let vec_ptr = vec.as_mut_ptr();
1918     ///     vec_ptr.write_bytes(b'a', 2);
1919     /// }
1920     /// assert_eq!(vec, [b'a', b'a', 0, 0]);
1921     /// ```
1922     #[stable(feature = "pointer_methods", since = "1.26.0")]
1923     #[inline]
1924     pub unsafe fn write_bytes(self, val: u8, count: usize)
1925         where T: Sized,
1926     {
1927         write_bytes(self, val, count)
1928     }
1929
1930     /// Performs a volatile write of a memory location with the given value without
1931     /// reading or dropping the old value.
1932     ///
1933     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1934     /// to not be elided or reordered by the compiler across other volatile
1935     /// operations.
1936     ///
1937     /// # Notes
1938     ///
1939     /// Rust does not currently have a rigorously and formally defined memory model,
1940     /// so the precise semantics of what "volatile" means here is subject to change
1941     /// over time. That being said, the semantics will almost always end up pretty
1942     /// similar to [C11's definition of volatile][c11].
1943     ///
1944     /// The compiler shouldn't change the relative order or number of volatile
1945     /// memory operations. However, volatile memory operations on zero-sized types
1946     /// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops
1947     /// and may be ignored.
1948     ///
1949     /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1950     ///
1951     /// # Safety
1952     ///
1953     /// This operation is marked unsafe because it accepts a raw pointer.
1954     ///
1955     /// It does not drop the contents of `self`. This is safe, but it could leak
1956     /// allocations or resources, so care must be taken not to overwrite an object
1957     /// that should be dropped.
1958     ///
1959     /// This is appropriate for initializing uninitialized memory, or overwriting
1960     /// memory that has previously been `read` from.
1961     ///
1962     /// # Examples
1963     ///
1964     /// Basic usage:
1965     ///
1966     /// ```
1967     /// let mut x = 0;
1968     /// let y = &mut x as *mut i32;
1969     /// let z = 12;
1970     ///
1971     /// unsafe {
1972     ///     y.write_volatile(z);
1973     ///     assert_eq!(y.read_volatile(), 12);
1974     /// }
1975     /// ```
1976     #[stable(feature = "pointer_methods", since = "1.26.0")]
1977     #[inline]
1978     pub unsafe fn write_volatile(self, val: T)
1979         where T: Sized,
1980     {
1981         write_volatile(self, val)
1982     }
1983
1984     /// Overwrites a memory location with the given value without reading or
1985     /// dropping the old value.
1986     ///
1987     /// Unlike `write`, the pointer may be unaligned.
1988     ///
1989     /// # Safety
1990     ///
1991     /// This operation is marked unsafe because it writes through a raw pointer.
1992     ///
1993     /// It does not drop the contents of `self`. This is safe, but it could leak
1994     /// allocations or resources, so care must be taken not to overwrite an object
1995     /// that should be dropped.
1996     ///
1997     /// Additionally, it does not drop `self`. Semantically, `self` is moved into the
1998     /// location pointed to by `val`.
1999     ///
2000     /// This is appropriate for initializing uninitialized memory, or overwriting
2001     /// memory that has previously been `read` from.
2002     ///
2003     /// # Examples
2004     ///
2005     /// Basic usage:
2006     ///
2007     /// ```
2008     /// let mut x = 0;
2009     /// let y = &mut x as *mut i32;
2010     /// let z = 12;
2011     ///
2012     /// unsafe {
2013     ///     y.write_unaligned(z);
2014     ///     assert_eq!(y.read_unaligned(), 12);
2015     /// }
2016     /// ```
2017     #[stable(feature = "pointer_methods", since = "1.26.0")]
2018     #[inline]
2019     pub unsafe fn write_unaligned(self, val: T)
2020         where T: Sized,
2021     {
2022         write_unaligned(self, val)
2023     }
2024
2025     /// Replaces the value at `self` with `src`, returning the old
2026     /// value, without dropping either.
2027     ///
2028     /// # Safety
2029     ///
2030     /// This is only unsafe because it accepts a raw pointer.
2031     /// Otherwise, this operation is identical to `mem::replace`.
2032     #[stable(feature = "pointer_methods", since = "1.26.0")]
2033     #[inline]
2034     pub unsafe fn replace(self, src: T) -> T
2035         where T: Sized,
2036     {
2037         replace(self, src)
2038     }
2039
2040     /// Swaps the values at two mutable locations of the same type, without
2041     /// deinitializing either. They may overlap, unlike `mem::swap` which is
2042     /// otherwise equivalent.
2043     ///
2044     /// # Safety
2045     ///
2046     /// This function copies the memory through the raw pointers passed to it
2047     /// as arguments.
2048     ///
2049     /// Ensure that these pointers are valid before calling `swap`.
2050     #[stable(feature = "pointer_methods", since = "1.26.0")]
2051     #[inline]
2052     pub unsafe fn swap(self, with: *mut T)
2053         where T: Sized,
2054     {
2055         swap(self, with)
2056     }
2057 }
2058
2059 // Equality for pointers
2060 #[stable(feature = "rust1", since = "1.0.0")]
2061 impl<T: ?Sized> PartialEq for *const T {
2062     #[inline]
2063     fn eq(&self, other: &*const T) -> bool { *self == *other }
2064 }
2065
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 impl<T: ?Sized> Eq for *const T {}
2068
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 impl<T: ?Sized> PartialEq for *mut T {
2071     #[inline]
2072     fn eq(&self, other: &*mut T) -> bool { *self == *other }
2073 }
2074
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 impl<T: ?Sized> Eq for *mut T {}
2077
2078 /// Compare raw pointers for equality.
2079 ///
2080 /// This is the same as using the `==` operator, but less generic:
2081 /// the arguments have to be `*const T` raw pointers,
2082 /// not anything that implements `PartialEq`.
2083 ///
2084 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2085 /// by their address rather than comparing the values they point to
2086 /// (which is what the `PartialEq for &T` implementation does).
2087 ///
2088 /// # Examples
2089 ///
2090 /// ```
2091 /// use std::ptr;
2092 ///
2093 /// let five = 5;
2094 /// let other_five = 5;
2095 /// let five_ref = &five;
2096 /// let same_five_ref = &five;
2097 /// let other_five_ref = &other_five;
2098 ///
2099 /// assert!(five_ref == same_five_ref);
2100 /// assert!(five_ref == other_five_ref);
2101 ///
2102 /// assert!(ptr::eq(five_ref, same_five_ref));
2103 /// assert!(!ptr::eq(five_ref, other_five_ref));
2104 /// ```
2105 #[stable(feature = "ptr_eq", since = "1.17.0")]
2106 #[inline]
2107 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2108     a == b
2109 }
2110
2111 // Impls for function pointers
2112 macro_rules! fnptr_impls_safety_abi {
2113     ($FnTy: ty, $($Arg: ident),*) => {
2114         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2115         impl<Ret, $($Arg),*> PartialEq for $FnTy {
2116             #[inline]
2117             fn eq(&self, other: &Self) -> bool {
2118                 *self as usize == *other as usize
2119             }
2120         }
2121
2122         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2123         impl<Ret, $($Arg),*> Eq for $FnTy {}
2124
2125         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2126         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2127             #[inline]
2128             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2129                 (*self as usize).partial_cmp(&(*other as usize))
2130             }
2131         }
2132
2133         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2134         impl<Ret, $($Arg),*> Ord for $FnTy {
2135             #[inline]
2136             fn cmp(&self, other: &Self) -> Ordering {
2137                 (*self as usize).cmp(&(*other as usize))
2138             }
2139         }
2140
2141         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2142         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2143             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2144                 state.write_usize(*self as usize)
2145             }
2146         }
2147
2148         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2149         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2150             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2151                 fmt::Pointer::fmt(&(*self as *const ()), f)
2152             }
2153         }
2154
2155         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2156         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2157             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2158                 fmt::Pointer::fmt(&(*self as *const ()), f)
2159             }
2160         }
2161     }
2162 }
2163
2164 macro_rules! fnptr_impls_args {
2165     ($($Arg: ident),+) => {
2166         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2167         fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2168         fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2169         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2170         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2171         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2172     };
2173     () => {
2174         // No variadic functions with 0 parameters
2175         fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2176         fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2177         fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2178         fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2179     };
2180 }
2181
2182 fnptr_impls_args! { }
2183 fnptr_impls_args! { A }
2184 fnptr_impls_args! { A, B }
2185 fnptr_impls_args! { A, B, C }
2186 fnptr_impls_args! { A, B, C, D }
2187 fnptr_impls_args! { A, B, C, D, E }
2188 fnptr_impls_args! { A, B, C, D, E, F }
2189 fnptr_impls_args! { A, B, C, D, E, F, G }
2190 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2191 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2192 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2193 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2194 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2195
2196 // Comparison for pointers
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 impl<T: ?Sized> Ord for *const T {
2199     #[inline]
2200     fn cmp(&self, other: &*const T) -> Ordering {
2201         if self < other {
2202             Less
2203         } else if self == other {
2204             Equal
2205         } else {
2206             Greater
2207         }
2208     }
2209 }
2210
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 impl<T: ?Sized> PartialOrd for *const T {
2213     #[inline]
2214     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2215         Some(self.cmp(other))
2216     }
2217
2218     #[inline]
2219     fn lt(&self, other: &*const T) -> bool { *self < *other }
2220
2221     #[inline]
2222     fn le(&self, other: &*const T) -> bool { *self <= *other }
2223
2224     #[inline]
2225     fn gt(&self, other: &*const T) -> bool { *self > *other }
2226
2227     #[inline]
2228     fn ge(&self, other: &*const T) -> bool { *self >= *other }
2229 }
2230
2231 #[stable(feature = "rust1", since = "1.0.0")]
2232 impl<T: ?Sized> Ord for *mut T {
2233     #[inline]
2234     fn cmp(&self, other: &*mut T) -> Ordering {
2235         if self < other {
2236             Less
2237         } else if self == other {
2238             Equal
2239         } else {
2240             Greater
2241         }
2242     }
2243 }
2244
2245 #[stable(feature = "rust1", since = "1.0.0")]
2246 impl<T: ?Sized> PartialOrd for *mut T {
2247     #[inline]
2248     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2249         Some(self.cmp(other))
2250     }
2251
2252     #[inline]
2253     fn lt(&self, other: &*mut T) -> bool { *self < *other }
2254
2255     #[inline]
2256     fn le(&self, other: &*mut T) -> bool { *self <= *other }
2257
2258     #[inline]
2259     fn gt(&self, other: &*mut T) -> bool { *self > *other }
2260
2261     #[inline]
2262     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
2263 }
2264
2265 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
2266 /// of this wrapper owns the referent. Useful for building abstractions like
2267 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
2268 ///
2269 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
2270 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
2271 /// the kind of strong aliasing guarantees an instance of `T` can expect:
2272 /// the referent of the pointer should not be modified without a unique path to
2273 /// its owning Unique.
2274 ///
2275 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
2276 /// consider using `NonNull`, which has weaker semantics.
2277 ///
2278 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2279 /// is never dereferenced. This is so that enums may use this forbidden value
2280 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
2281 /// However the pointer may still dangle if it isn't dereferenced.
2282 ///
2283 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
2284 /// for any type which upholds Unique's aliasing requirements.
2285 #[unstable(feature = "ptr_internals", issue = "0",
2286            reason = "use NonNull instead and consider PhantomData<T> \
2287                      (if you also use #[may_dangle]), Send, and/or Sync")]
2288 #[allow(deprecated)]
2289 pub struct Unique<T: ?Sized> {
2290     pointer: NonZero<*const T>,
2291     // NOTE: this marker has no consequences for variance, but is necessary
2292     // for dropck to understand that we logically own a `T`.
2293     //
2294     // For details, see:
2295     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
2296     _marker: PhantomData<T>,
2297 }
2298
2299 #[unstable(feature = "ptr_internals", issue = "0")]
2300 impl<T: ?Sized> fmt::Debug for Unique<T> {
2301     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2302         fmt::Pointer::fmt(&self.as_ptr(), f)
2303     }
2304 }
2305
2306 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
2307 /// reference is unaliased. Note that this aliasing invariant is
2308 /// unenforced by the type system; the abstraction using the
2309 /// `Unique` must enforce it.
2310 #[unstable(feature = "ptr_internals", issue = "0")]
2311 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
2312
2313 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
2314 /// reference is unaliased. Note that this aliasing invariant is
2315 /// unenforced by the type system; the abstraction using the
2316 /// `Unique` must enforce it.
2317 #[unstable(feature = "ptr_internals", issue = "0")]
2318 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
2319
2320 #[unstable(feature = "ptr_internals", issue = "0")]
2321 impl<T: Sized> Unique<T> {
2322     /// Creates a new `Unique` that is dangling, but well-aligned.
2323     ///
2324     /// This is useful for initializing types which lazily allocate, like
2325     /// `Vec::new` does.
2326     // FIXME: rename to dangling() to match NonNull?
2327     pub fn empty() -> Self {
2328         unsafe {
2329             let ptr = mem::align_of::<T>() as *mut T;
2330             Unique::new_unchecked(ptr)
2331         }
2332     }
2333 }
2334
2335 #[unstable(feature = "ptr_internals", issue = "0")]
2336 #[allow(deprecated)]
2337 impl<T: ?Sized> Unique<T> {
2338     /// Creates a new `Unique`.
2339     ///
2340     /// # Safety
2341     ///
2342     /// `ptr` must be non-null.
2343     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2344         Unique { pointer: NonZero(ptr as _), _marker: PhantomData }
2345     }
2346
2347     /// Creates a new `Unique` if `ptr` is non-null.
2348     pub fn new(ptr: *mut T) -> Option<Self> {
2349         if !ptr.is_null() {
2350             Some(Unique { pointer: NonZero(ptr as _), _marker: PhantomData })
2351         } else {
2352             None
2353         }
2354     }
2355
2356     /// Acquires the underlying `*mut` pointer.
2357     pub fn as_ptr(self) -> *mut T {
2358         self.pointer.0 as *mut T
2359     }
2360
2361     /// Dereferences the content.
2362     ///
2363     /// The resulting lifetime is bound to self so this behaves "as if"
2364     /// it were actually an instance of T that is getting borrowed. If a longer
2365     /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2366     pub unsafe fn as_ref(&self) -> &T {
2367         &*self.as_ptr()
2368     }
2369
2370     /// Mutably dereferences the content.
2371     ///
2372     /// The resulting lifetime is bound to self so this behaves "as if"
2373     /// it were actually an instance of T that is getting borrowed. If a longer
2374     /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2375     pub unsafe fn as_mut(&mut self) -> &mut T {
2376         &mut *self.as_ptr()
2377     }
2378 }
2379
2380 #[unstable(feature = "ptr_internals", issue = "0")]
2381 impl<T: ?Sized> Clone for Unique<T> {
2382     fn clone(&self) -> Self {
2383         *self
2384     }
2385 }
2386
2387 #[unstable(feature = "ptr_internals", issue = "0")]
2388 impl<T: ?Sized> Copy for Unique<T> { }
2389
2390 #[unstable(feature = "ptr_internals", issue = "0")]
2391 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
2392
2393 #[unstable(feature = "ptr_internals", issue = "0")]
2394 impl<T: ?Sized> fmt::Pointer for Unique<T> {
2395     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2396         fmt::Pointer::fmt(&self.as_ptr(), f)
2397     }
2398 }
2399
2400 #[unstable(feature = "ptr_internals", issue = "0")]
2401 #[allow(deprecated)]
2402 impl<'a, T: ?Sized> From<&'a mut T> for Unique<T> {
2403     fn from(reference: &'a mut T) -> Self {
2404         Unique { pointer: NonZero(reference as _), _marker: PhantomData }
2405     }
2406 }
2407
2408 #[unstable(feature = "ptr_internals", issue = "0")]
2409 #[allow(deprecated)]
2410 impl<'a, T: ?Sized> From<&'a T> for Unique<T> {
2411     fn from(reference: &'a T) -> Self {
2412         Unique { pointer: NonZero(reference as _), _marker: PhantomData }
2413     }
2414 }
2415
2416 #[unstable(feature = "ptr_internals", issue = "0")]
2417 impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
2418     fn from(p: NonNull<T>) -> Self {
2419         Unique { pointer: p.pointer, _marker: PhantomData }
2420     }
2421 }
2422
2423 /// Previous name of `NonNull`.
2424 #[rustc_deprecated(since = "1.25.0", reason = "renamed to `NonNull`")]
2425 #[unstable(feature = "shared", issue = "27730")]
2426 pub type Shared<T> = NonNull<T>;
2427
2428 /// `*mut T` but non-zero and covariant.
2429 ///
2430 /// This is often the correct thing to use when building data structures using
2431 /// raw pointers, but is ultimately more dangerous to use because of its additional
2432 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
2433 ///
2434 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2435 /// is never dereferenced. This is so that enums may use this forbidden value
2436 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `NonNull<T>`.
2437 /// However the pointer may still dangle if it isn't dereferenced.
2438 ///
2439 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
2440 /// for your use case, you should include some PhantomData in your type to
2441 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
2442 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
2443 /// such as Box, Rc, Arc, Vec, and LinkedList. This is the case because they
2444 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
2445 #[stable(feature = "nonnull", since = "1.25.0")]
2446 pub struct NonNull<T: ?Sized> {
2447     #[allow(deprecated)] pointer: NonZero<*const T>,
2448 }
2449
2450 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
2451 // NB: This impl is unnecessary, but should provide better error messages.
2452 #[stable(feature = "nonnull", since = "1.25.0")]
2453 impl<T: ?Sized> !Send for NonNull<T> { }
2454
2455 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
2456 // NB: This impl is unnecessary, but should provide better error messages.
2457 #[stable(feature = "nonnull", since = "1.25.0")]
2458 impl<T: ?Sized> !Sync for NonNull<T> { }
2459
2460 impl<T: Sized> NonNull<T> {
2461     /// Creates a new `NonNull` that is dangling, but well-aligned.
2462     ///
2463     /// This is useful for initializing types which lazily allocate, like
2464     /// `Vec::new` does.
2465     #[stable(feature = "nonnull", since = "1.25.0")]
2466     pub fn dangling() -> Self {
2467         unsafe {
2468             let ptr = mem::align_of::<T>() as *mut T;
2469             NonNull::new_unchecked(ptr)
2470         }
2471     }
2472 }
2473
2474 #[allow(deprecated)]
2475 impl<T: ?Sized> NonNull<T> {
2476     /// Creates a new `NonNull`.
2477     ///
2478     /// # Safety
2479     ///
2480     /// `ptr` must be non-null.
2481     #[stable(feature = "nonnull", since = "1.25.0")]
2482     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2483         NonNull { pointer: NonZero(ptr as _) }
2484     }
2485
2486     /// Creates a new `NonNull` if `ptr` is non-null.
2487     #[stable(feature = "nonnull", since = "1.25.0")]
2488     pub fn new(ptr: *mut T) -> Option<Self> {
2489         if !ptr.is_null() {
2490             Some(NonNull { pointer: NonZero(ptr as _) })
2491         } else {
2492             None
2493         }
2494     }
2495
2496     /// Acquires the underlying `*mut` pointer.
2497     #[stable(feature = "nonnull", since = "1.25.0")]
2498     pub fn as_ptr(self) -> *mut T {
2499         self.pointer.0 as *mut T
2500     }
2501
2502     /// Dereferences the content.
2503     ///
2504     /// The resulting lifetime is bound to self so this behaves "as if"
2505     /// it were actually an instance of T that is getting borrowed. If a longer
2506     /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2507     #[stable(feature = "nonnull", since = "1.25.0")]
2508     pub unsafe fn as_ref(&self) -> &T {
2509         &*self.as_ptr()
2510     }
2511
2512     /// Mutably dereferences the content.
2513     ///
2514     /// The resulting lifetime is bound to self so this behaves "as if"
2515     /// it were actually an instance of T that is getting borrowed. If a longer
2516     /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2517     #[stable(feature = "nonnull", since = "1.25.0")]
2518     pub unsafe fn as_mut(&mut self) -> &mut T {
2519         &mut *self.as_ptr()
2520     }
2521
2522     /// Cast to a pointer of another type
2523     #[unstable(feature = "nonnull_cast", issue = "47653")]
2524     pub fn cast<U>(self) -> NonNull<U> {
2525         unsafe {
2526             NonNull::new_unchecked(self.as_ptr() as *mut U)
2527         }
2528     }
2529 }
2530
2531 #[stable(feature = "nonnull", since = "1.25.0")]
2532 impl<T: ?Sized> Clone for NonNull<T> {
2533     fn clone(&self) -> Self {
2534         *self
2535     }
2536 }
2537
2538 #[stable(feature = "nonnull", since = "1.25.0")]
2539 impl<T: ?Sized> Copy for NonNull<T> { }
2540
2541 #[unstable(feature = "coerce_unsized", issue = "27732")]
2542 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
2543
2544 #[stable(feature = "nonnull", since = "1.25.0")]
2545 impl<T: ?Sized> fmt::Debug for NonNull<T> {
2546     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2547         fmt::Pointer::fmt(&self.as_ptr(), f)
2548     }
2549 }
2550
2551 #[stable(feature = "nonnull", since = "1.25.0")]
2552 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
2553     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2554         fmt::Pointer::fmt(&self.as_ptr(), f)
2555     }
2556 }
2557
2558 #[stable(feature = "nonnull", since = "1.25.0")]
2559 impl<T: ?Sized> Eq for NonNull<T> {}
2560
2561 #[stable(feature = "nonnull", since = "1.25.0")]
2562 impl<T: ?Sized> PartialEq for NonNull<T> {
2563     fn eq(&self, other: &Self) -> bool {
2564         self.as_ptr() == other.as_ptr()
2565     }
2566 }
2567
2568 #[stable(feature = "nonnull", since = "1.25.0")]
2569 impl<T: ?Sized> Ord for NonNull<T> {
2570     fn cmp(&self, other: &Self) -> Ordering {
2571         self.as_ptr().cmp(&other.as_ptr())
2572     }
2573 }
2574
2575 #[stable(feature = "nonnull", since = "1.25.0")]
2576 impl<T: ?Sized> PartialOrd for NonNull<T> {
2577     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2578         self.as_ptr().partial_cmp(&other.as_ptr())
2579     }
2580 }
2581
2582 #[stable(feature = "nonnull", since = "1.25.0")]
2583 impl<T: ?Sized> hash::Hash for NonNull<T> {
2584     fn hash<H: hash::Hasher>(&self, state: &mut H) {
2585         self.as_ptr().hash(state)
2586     }
2587 }
2588
2589 #[unstable(feature = "ptr_internals", issue = "0")]
2590 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
2591     fn from(unique: Unique<T>) -> Self {
2592         NonNull { pointer: unique.pointer }
2593     }
2594 }
2595
2596 #[stable(feature = "nonnull", since = "1.25.0")]
2597 #[allow(deprecated)]
2598 impl<'a, T: ?Sized> From<&'a mut T> for NonNull<T> {
2599     fn from(reference: &'a mut T) -> Self {
2600         NonNull { pointer: NonZero(reference as _) }
2601     }
2602 }
2603
2604 #[stable(feature = "nonnull", since = "1.25.0")]
2605 #[allow(deprecated)]
2606 impl<'a, T: ?Sized> From<&'a T> for NonNull<T> {
2607     fn from(reference: &'a T) -> Self {
2608         NonNull { pointer: NonZero(reference as _) }
2609     }
2610 }