]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
cbd45bb6a39e191d2a5f91177057a7837b4175c1
[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 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 distance between two pointers. The returned value is in
704     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
705     ///
706     /// This function is the inverse of [`offset`].
707     ///
708     /// [`offset`]: #method.offset
709     /// [`wrapping_offset_from`]: #method.wrapping_offset_from
710     ///
711     /// # Safety
712     ///
713     /// If any of the following conditions are violated, the result is Undefined
714     /// Behavior:
715     ///
716     /// * Both the starting and other pointer must be either in bounds or one
717     ///   byte past the end of the same allocated object.
718     ///
719     /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
720     ///
721     /// * The distance between the pointers, in bytes, must be an exact multiple
722     ///   of the size of `T` and `T` must not be a Zero-Sized Type ("ZST").
723     ///
724     /// * The distance being in bounds cannot rely on "wrapping around" the address space.
725     ///
726     /// The compiler and standard library generally try to ensure allocations
727     /// never reach a size where an offset is a concern. For instance, `Vec`
728     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
729     /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
730     ///
731     /// Most platforms fundamentally can't even construct such an allocation.
732     /// For instance, no known 64-bit platform can ever serve a request
733     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
734     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
735     /// more than `isize::MAX` bytes with things like Physical Address
736     /// Extension. As such, memory acquired directly from allocators or memory
737     /// mapped files *may* be too large to handle with this function.
738     ///
739     /// Consider using [`wrapping_offset_from`] instead if these constraints are
740     /// difficult to satisfy. The only advantage of this method is that it
741     /// enables more aggressive compiler optimizations.
742     ///
743     /// # Examples
744     ///
745     /// Basic usage:
746     ///
747     /// ```
748     /// #![feature(ptr_offset_from)]
749     ///
750     /// let a = [0; 5];
751     /// let ptr1: *const i32 = &a[1];
752     /// let ptr2: *const i32 = &a[3];
753     /// unsafe {
754     ///     assert_eq!(ptr2.offset_from(ptr1), 2);
755     ///     assert_eq!(ptr1.offset_from(ptr2), -2);
756     ///     assert_eq!(ptr1.offset(2), ptr2);
757     ///     assert_eq!(ptr2.offset(-2), ptr1);
758     /// }
759     /// ```
760     #[unstable(feature = "ptr_offset_from", issue = "41079")]
761     #[inline]
762     pub unsafe fn offset_from(self, other: *const T) -> isize where T: Sized {
763         let pointee_size = mem::size_of::<T>();
764         assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
765
766         // FIXME: can this be nuw/nsw?
767         let d = isize::wrapping_sub(self as _, other as _);
768         intrinsics::exact_div(d, pointee_size as _)
769     }
770
771     /// Calculates the distance between two pointers. The returned value is in
772     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
773     ///
774     /// If the address different between the two pointers is not a multiple of
775     /// `mem::size_of::<T>()` then the result of the division is rounded towards
776     /// zero.
777     ///
778     /// # Panics
779     ///
780     /// This function panics if `T` is a zero-sized typed.
781     ///
782     /// # Examples
783     ///
784     /// Basic usage:
785     ///
786     /// ```
787     /// #![feature(ptr_wrapping_offset_from)]
788     ///
789     /// let a = [0; 5];
790     /// let ptr1: *const i32 = &a[1];
791     /// let ptr2: *const i32 = &a[3];
792     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
793     /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
794     /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
795     /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
796     ///
797     /// let ptr1: *const i32 = 3 as _;
798     /// let ptr2: *const i32 = 13 as _;
799     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
800     /// ```
801     #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
802     #[inline]
803     pub fn wrapping_offset_from(self, other: *const T) -> isize where T: Sized {
804         let pointee_size = mem::size_of::<T>();
805         assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
806
807         let d = isize::wrapping_sub(self as _, other as _);
808         d.wrapping_div(pointee_size as _)
809     }
810
811     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
812     ///
813     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
814     /// offset of `3 * size_of::<T>()` bytes.
815     ///
816     /// # Safety
817     ///
818     /// If any of the following conditions are violated, the result is Undefined
819     /// Behavior:
820     ///
821     /// * Both the starting and resulting pointer must be either in bounds or one
822     ///   byte past the end of an allocated object.
823     ///
824     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
825     ///
826     /// * The offset being in bounds cannot rely on "wrapping around" the address
827     ///   space. That is, the infinite-precision sum must fit in a `usize`.
828     ///
829     /// The compiler and standard library generally tries to ensure allocations
830     /// never reach a size where an offset is a concern. For instance, `Vec`
831     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
832     /// `vec.as_ptr().add(vec.len())` is always safe.
833     ///
834     /// Most platforms fundamentally can't even construct such an allocation.
835     /// For instance, no known 64-bit platform can ever serve a request
836     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
837     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
838     /// more than `isize::MAX` bytes with things like Physical Address
839     /// Extension. As such, memory acquired directly from allocators or memory
840     /// mapped files *may* be too large to handle with this function.
841     ///
842     /// Consider using `wrapping_offset` instead if these constraints are
843     /// difficult to satisfy. The only advantage of this method is that it
844     /// enables more aggressive compiler optimizations.
845     ///
846     /// # Examples
847     ///
848     /// Basic usage:
849     ///
850     /// ```
851     /// let s: &str = "123";
852     /// let ptr: *const u8 = s.as_ptr();
853     ///
854     /// unsafe {
855     ///     println!("{}", *ptr.add(1) as char);
856     ///     println!("{}", *ptr.add(2) as char);
857     /// }
858     /// ```
859     #[stable(feature = "pointer_methods", since = "1.26.0")]
860     #[inline]
861     pub unsafe fn add(self, count: usize) -> Self
862         where T: Sized,
863     {
864         self.offset(count as isize)
865     }
866
867     /// Calculates the offset from a pointer (convenience for
868     /// `.offset((count as isize).wrapping_neg())`).
869     ///
870     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
871     /// offset of `3 * size_of::<T>()` bytes.
872     ///
873     /// # Safety
874     ///
875     /// If any of the following conditions are violated, the result is Undefined
876     /// Behavior:
877     ///
878     /// * Both the starting and resulting pointer must be either in bounds or one
879     ///   byte past the end of an allocated object.
880     ///
881     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
882     ///
883     /// * The offset being in bounds cannot rely on "wrapping around" the address
884     ///   space. That is, the infinite-precision sum must fit in a usize.
885     ///
886     /// The compiler and standard library generally tries to ensure allocations
887     /// never reach a size where an offset is a concern. For instance, `Vec`
888     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
889     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
890     ///
891     /// Most platforms fundamentally can't even construct such an allocation.
892     /// For instance, no known 64-bit platform can ever serve a request
893     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
894     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
895     /// more than `isize::MAX` bytes with things like Physical Address
896     /// Extension. As such, memory acquired directly from allocators or memory
897     /// mapped files *may* be too large to handle with this function.
898     ///
899     /// Consider using `wrapping_offset` instead if these constraints are
900     /// difficult to satisfy. The only advantage of this method is that it
901     /// enables more aggressive compiler optimizations.
902     ///
903     /// # Examples
904     ///
905     /// Basic usage:
906     ///
907     /// ```
908     /// let s: &str = "123";
909     ///
910     /// unsafe {
911     ///     let end: *const u8 = s.as_ptr().add(3);
912     ///     println!("{}", *end.sub(1) as char);
913     ///     println!("{}", *end.sub(2) as char);
914     /// }
915     /// ```
916     #[stable(feature = "pointer_methods", since = "1.26.0")]
917     #[inline]
918     pub unsafe fn sub(self, count: usize) -> Self
919         where T: Sized,
920     {
921         self.offset((count as isize).wrapping_neg())
922     }
923
924     /// Calculates the offset from a pointer using wrapping arithmetic.
925     /// (convenience for `.wrapping_offset(count as isize)`)
926     ///
927     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
928     /// offset of `3 * size_of::<T>()` bytes.
929     ///
930     /// # Safety
931     ///
932     /// The resulting pointer does not need to be in bounds, but it is
933     /// potentially hazardous to dereference (which requires `unsafe`).
934     ///
935     /// Always use `.add(count)` instead when possible, because `add`
936     /// allows the compiler to optimize better.
937     ///
938     /// # Examples
939     ///
940     /// Basic usage:
941     ///
942     /// ```
943     /// // Iterate using a raw pointer in increments of two elements
944     /// let data = [1u8, 2, 3, 4, 5];
945     /// let mut ptr: *const u8 = data.as_ptr();
946     /// let step = 2;
947     /// let end_rounded_up = ptr.wrapping_add(6);
948     ///
949     /// // This loop prints "1, 3, 5, "
950     /// while ptr != end_rounded_up {
951     ///     unsafe {
952     ///         print!("{}, ", *ptr);
953     ///     }
954     ///     ptr = ptr.wrapping_add(step);
955     /// }
956     /// ```
957     #[stable(feature = "pointer_methods", since = "1.26.0")]
958     #[inline]
959     pub fn wrapping_add(self, count: usize) -> Self
960         where T: Sized,
961     {
962         self.wrapping_offset(count as isize)
963     }
964
965     /// Calculates the offset from a pointer using wrapping arithmetic.
966     /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
967     ///
968     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
969     /// offset of `3 * size_of::<T>()` bytes.
970     ///
971     /// # Safety
972     ///
973     /// The resulting pointer does not need to be in bounds, but it is
974     /// potentially hazardous to dereference (which requires `unsafe`).
975     ///
976     /// Always use `.sub(count)` instead when possible, because `sub`
977     /// allows the compiler to optimize better.
978     ///
979     /// # Examples
980     ///
981     /// Basic usage:
982     ///
983     /// ```
984     /// // Iterate using a raw pointer in increments of two elements (backwards)
985     /// let data = [1u8, 2, 3, 4, 5];
986     /// let mut ptr: *const u8 = data.as_ptr();
987     /// let start_rounded_down = ptr.wrapping_sub(2);
988     /// ptr = ptr.wrapping_add(4);
989     /// let step = 2;
990     /// // This loop prints "5, 3, 1, "
991     /// while ptr != start_rounded_down {
992     ///     unsafe {
993     ///         print!("{}, ", *ptr);
994     ///     }
995     ///     ptr = ptr.wrapping_sub(step);
996     /// }
997     /// ```
998     #[stable(feature = "pointer_methods", since = "1.26.0")]
999     #[inline]
1000     pub fn wrapping_sub(self, count: usize) -> Self
1001         where T: Sized,
1002     {
1003         self.wrapping_offset((count as isize).wrapping_neg())
1004     }
1005
1006     /// Reads the value from `self` without moving it. This leaves the
1007     /// memory in `self` unchanged.
1008     ///
1009     /// # Safety
1010     ///
1011     /// Beyond accepting a raw pointer, this is unsafe because it semantically
1012     /// moves the value out of `self` without preventing further usage of `self`.
1013     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1014     /// `self` is not used before the data is overwritten again (e.g. with `write`,
1015     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1016     /// because it will attempt to drop the value previously at `*self`.
1017     ///
1018     /// The pointer must be aligned; use `read_unaligned` if that is not the case.
1019     ///
1020     /// # Examples
1021     ///
1022     /// Basic usage:
1023     ///
1024     /// ```
1025     /// let x = 12;
1026     /// let y = &x as *const i32;
1027     ///
1028     /// unsafe {
1029     ///     assert_eq!(y.read(), 12);
1030     /// }
1031     /// ```
1032     #[stable(feature = "pointer_methods", since = "1.26.0")]
1033     #[inline]
1034     pub unsafe fn read(self) -> T
1035         where T: Sized,
1036     {
1037         read(self)
1038     }
1039
1040     /// Performs a volatile read of the value from `self` without moving it. This
1041     /// leaves the memory in `self` unchanged.
1042     ///
1043     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1044     /// to not be elided or reordered by the compiler across other volatile
1045     /// operations.
1046     ///
1047     /// # Notes
1048     ///
1049     /// Rust does not currently have a rigorously and formally defined memory model,
1050     /// so the precise semantics of what "volatile" means here is subject to change
1051     /// over time. That being said, the semantics will almost always end up pretty
1052     /// similar to [C11's definition of volatile][c11].
1053     ///
1054     /// The compiler shouldn't change the relative order or number of volatile
1055     /// memory operations. However, volatile memory operations on zero-sized types
1056     /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
1057     /// and may be ignored.
1058     ///
1059     /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1060     ///
1061     /// # Safety
1062     ///
1063     /// Beyond accepting a raw pointer, this is unsafe because it semantically
1064     /// moves the value out of `self` without preventing further usage of `self`.
1065     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1066     /// `self` is not used before the data is overwritten again (e.g. with `write`,
1067     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1068     /// because it will attempt to drop the value previously at `*self`.
1069     ///
1070     /// # Examples
1071     ///
1072     /// Basic usage:
1073     ///
1074     /// ```
1075     /// let x = 12;
1076     /// let y = &x as *const i32;
1077     ///
1078     /// unsafe {
1079     ///     assert_eq!(y.read_volatile(), 12);
1080     /// }
1081     /// ```
1082     #[stable(feature = "pointer_methods", since = "1.26.0")]
1083     #[inline]
1084     pub unsafe fn read_volatile(self) -> T
1085         where T: Sized,
1086     {
1087         read_volatile(self)
1088     }
1089
1090     /// Reads the value from `self` without moving it. This leaves the
1091     /// memory in `self` unchanged.
1092     ///
1093     /// Unlike `read`, the pointer may be unaligned.
1094     ///
1095     /// # Safety
1096     ///
1097     /// Beyond accepting a raw pointer, this is unsafe because it semantically
1098     /// moves the value out of `self` without preventing further usage of `self`.
1099     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1100     /// `self` is not used before the data is overwritten again (e.g. with `write`,
1101     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1102     /// because it will attempt to drop the value previously at `*self`.
1103     ///
1104     /// # Examples
1105     ///
1106     /// Basic usage:
1107     ///
1108     /// ```
1109     /// let x = 12;
1110     /// let y = &x as *const i32;
1111     ///
1112     /// unsafe {
1113     ///     assert_eq!(y.read_unaligned(), 12);
1114     /// }
1115     /// ```
1116     #[stable(feature = "pointer_methods", since = "1.26.0")]
1117     #[inline]
1118     pub unsafe fn read_unaligned(self) -> T
1119         where T: Sized,
1120     {
1121         read_unaligned(self)
1122     }
1123
1124     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1125     /// and destination may overlap.
1126     ///
1127     /// NOTE: this has the *same* argument order as `ptr::copy`.
1128     ///
1129     /// This is semantically equivalent to C's `memmove`.
1130     ///
1131     /// # Safety
1132     ///
1133     /// Care must be taken with the ownership of `self` and `dest`.
1134     /// This method semantically moves the values of `self` into `dest`.
1135     /// However it does not drop the contents of `self`, or prevent the contents
1136     /// of `dest` from being dropped or used.
1137     ///
1138     /// # Examples
1139     ///
1140     /// Efficiently create a Rust vector from an unsafe buffer:
1141     ///
1142     /// ```
1143     /// # #[allow(dead_code)]
1144     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1145     ///     let mut dst = Vec::with_capacity(elts);
1146     ///     dst.set_len(elts);
1147     ///     ptr.copy_to(dst.as_mut_ptr(), elts);
1148     ///     dst
1149     /// }
1150     /// ```
1151     #[stable(feature = "pointer_methods", since = "1.26.0")]
1152     #[inline]
1153     pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1154         where T: Sized,
1155     {
1156         copy(self, dest, count)
1157     }
1158
1159     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1160     /// and destination may *not* overlap.
1161     ///
1162     /// NOTE: this has the *same* argument order as `ptr::copy_nonoverlapping`.
1163     ///
1164     /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
1165     ///
1166     /// # Safety
1167     ///
1168     /// Beyond requiring that the program must be allowed to access both regions
1169     /// of memory, it is Undefined Behavior for source and destination to
1170     /// overlap. Care must also be taken with the ownership of `self` and
1171     /// `self`. This method semantically moves the values of `self` into `dest`.
1172     /// However it does not drop the contents of `dest`, or prevent the contents
1173     /// of `self` from being dropped or used.
1174     ///
1175     /// # Examples
1176     ///
1177     /// Efficiently create a Rust vector from an unsafe buffer:
1178     ///
1179     /// ```
1180     /// # #[allow(dead_code)]
1181     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1182     ///     let mut dst = Vec::with_capacity(elts);
1183     ///     dst.set_len(elts);
1184     ///     ptr.copy_to_nonoverlapping(dst.as_mut_ptr(), elts);
1185     ///     dst
1186     /// }
1187     /// ```
1188     #[stable(feature = "pointer_methods", since = "1.26.0")]
1189     #[inline]
1190     pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1191         where T: Sized,
1192     {
1193         copy_nonoverlapping(self, dest, count)
1194     }
1195
1196     /// Computes the byte offset that needs to be applied in order to
1197     /// make the pointer aligned to `align`.
1198     /// If it is not possible to align the pointer, the implementation returns
1199     /// `usize::max_value()`.
1200     ///
1201     /// There are no guarantees whatsover that offsetting the pointer will not
1202     /// overflow or go beyond the allocation that the pointer points into.
1203     /// It is up to the caller to ensure that the returned offset is correct
1204     /// in all terms other than alignment.
1205     ///
1206     /// # Examples
1207     ///
1208     /// Accessing adjacent `u8` as `u16`
1209     ///
1210     /// ```
1211     /// # #![feature(align_offset)]
1212     /// # fn foo(n: usize) {
1213     /// # use std::mem::align_of;
1214     /// # unsafe {
1215     /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1216     /// let ptr = &x[n] as *const u8;
1217     /// let offset = ptr.align_offset(align_of::<u16>());
1218     /// if offset < x.len() - n - 1 {
1219     ///     let u16_ptr = ptr.offset(offset as isize) as *const u16;
1220     ///     assert_ne!(*u16_ptr, 500);
1221     /// } else {
1222     ///     // while the pointer can be aligned via `offset`, it would point
1223     ///     // outside the allocation
1224     /// }
1225     /// # } }
1226     /// ```
1227     #[unstable(feature = "align_offset", issue = "44488")]
1228     pub fn align_offset(self, align: usize) -> usize {
1229         unsafe {
1230             intrinsics::align_offset(self as *const _, align)
1231         }
1232     }
1233 }
1234
1235 #[lang = "mut_ptr"]
1236 impl<T: ?Sized> *mut T {
1237     /// Returns `true` if the pointer is null.
1238     ///
1239     /// Note that unsized types have many possible null pointers, as only the
1240     /// raw data pointer is considered, not their length, vtable, etc.
1241     /// Therefore, two pointers that are null may still not compare equal to
1242     /// each other.
1243     ///
1244     /// # Examples
1245     ///
1246     /// Basic usage:
1247     ///
1248     /// ```
1249     /// let mut s = [1, 2, 3];
1250     /// let ptr: *mut u32 = s.as_mut_ptr();
1251     /// assert!(!ptr.is_null());
1252     /// ```
1253     #[stable(feature = "rust1", since = "1.0.0")]
1254     #[inline]
1255     pub fn is_null(self) -> bool {
1256         // Compare via a cast to a thin pointer, so fat pointers are only
1257         // considering their "data" part for null-ness.
1258         (self as *mut u8) == null_mut()
1259     }
1260
1261     /// Returns `None` if the pointer is null, or else returns a reference to
1262     /// the value wrapped in `Some`.
1263     ///
1264     /// # Safety
1265     ///
1266     /// While this method and its mutable counterpart are useful for
1267     /// null-safety, it is important to note that this is still an unsafe
1268     /// operation because the returned value could be pointing to invalid
1269     /// memory.
1270     ///
1271     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1272     /// not necessarily reflect the actual lifetime of the data.
1273     ///
1274     /// # Examples
1275     ///
1276     /// Basic usage:
1277     ///
1278     /// ```
1279     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1280     ///
1281     /// unsafe {
1282     ///     if let Some(val_back) = ptr.as_ref() {
1283     ///         println!("We got back the value: {}!", val_back);
1284     ///     }
1285     /// }
1286     /// ```
1287     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1288     #[inline]
1289     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1290         if self.is_null() {
1291             None
1292         } else {
1293             Some(&*self)
1294         }
1295     }
1296
1297     /// Calculates the offset from a pointer.
1298     ///
1299     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1300     /// offset of `3 * size_of::<T>()` bytes.
1301     ///
1302     /// # Safety
1303     ///
1304     /// If any of the following conditions are violated, the result is Undefined
1305     /// Behavior:
1306     ///
1307     /// * Both the starting and resulting pointer must be either in bounds or one
1308     ///   byte past the end of an allocated object.
1309     ///
1310     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1311     ///
1312     /// * The offset being in bounds cannot rely on "wrapping around" the address
1313     ///   space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1314     ///
1315     /// The compiler and standard library generally tries to ensure allocations
1316     /// never reach a size where an offset is a concern. For instance, `Vec`
1317     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1318     /// `vec.as_ptr().offset(vec.len() as isize)` is always safe.
1319     ///
1320     /// Most platforms fundamentally can't even construct such an allocation.
1321     /// For instance, no known 64-bit platform can ever serve a request
1322     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1323     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1324     /// more than `isize::MAX` bytes with things like Physical Address
1325     /// Extension. As such, memory acquired directly from allocators or memory
1326     /// mapped files *may* be too large to handle with this function.
1327     ///
1328     /// Consider using `wrapping_offset` instead if these constraints are
1329     /// difficult to satisfy. The only advantage of this method is that it
1330     /// enables more aggressive compiler optimizations.
1331     ///
1332     /// # Examples
1333     ///
1334     /// Basic usage:
1335     ///
1336     /// ```
1337     /// let mut s = [1, 2, 3];
1338     /// let ptr: *mut u32 = s.as_mut_ptr();
1339     ///
1340     /// unsafe {
1341     ///     println!("{}", *ptr.offset(1));
1342     ///     println!("{}", *ptr.offset(2));
1343     /// }
1344     /// ```
1345     #[stable(feature = "rust1", since = "1.0.0")]
1346     #[inline]
1347     pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1348         intrinsics::offset(self, count) as *mut T
1349     }
1350
1351     /// Calculates the offset from a pointer using wrapping arithmetic.
1352     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1353     /// offset of `3 * size_of::<T>()` bytes.
1354     ///
1355     /// # Safety
1356     ///
1357     /// The resulting pointer does not need to be in bounds, but it is
1358     /// potentially hazardous to dereference (which requires `unsafe`).
1359     ///
1360     /// Always use `.offset(count)` instead when possible, because `offset`
1361     /// allows the compiler to optimize better.
1362     ///
1363     /// # Examples
1364     ///
1365     /// Basic usage:
1366     ///
1367     /// ```
1368     /// // Iterate using a raw pointer in increments of two elements
1369     /// let mut data = [1u8, 2, 3, 4, 5];
1370     /// let mut ptr: *mut u8 = data.as_mut_ptr();
1371     /// let step = 2;
1372     /// let end_rounded_up = ptr.wrapping_offset(6);
1373     ///
1374     /// while ptr != end_rounded_up {
1375     ///     unsafe {
1376     ///         *ptr = 0;
1377     ///     }
1378     ///     ptr = ptr.wrapping_offset(step);
1379     /// }
1380     /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1381     /// ```
1382     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1383     #[inline]
1384     pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1385         unsafe {
1386             intrinsics::arith_offset(self, count) as *mut T
1387         }
1388     }
1389
1390     /// Returns `None` if the pointer is null, or else returns a mutable
1391     /// reference to the value wrapped in `Some`.
1392     ///
1393     /// # Safety
1394     ///
1395     /// As with `as_ref`, this is unsafe because it cannot verify the validity
1396     /// of the returned pointer, nor can it ensure that the lifetime `'a`
1397     /// returned is indeed a valid lifetime for the contained data.
1398     ///
1399     /// # Examples
1400     ///
1401     /// Basic usage:
1402     ///
1403     /// ```
1404     /// let mut s = [1, 2, 3];
1405     /// let ptr: *mut u32 = s.as_mut_ptr();
1406     /// let first_value = unsafe { ptr.as_mut().unwrap() };
1407     /// *first_value = 4;
1408     /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1409     /// ```
1410     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1411     #[inline]
1412     pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1413         if self.is_null() {
1414             None
1415         } else {
1416             Some(&mut *self)
1417         }
1418     }
1419
1420     /// Calculates the distance between two pointers. The returned value is in
1421     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1422     ///
1423     /// If the address different between the two pointers ia not a multiple of
1424     /// `mem::size_of::<T>()` then the result of the division is rounded towards
1425     /// zero.
1426     ///
1427     /// This function returns `None` if `T` is a zero-sized typed.
1428     ///
1429     /// # Examples
1430     ///
1431     /// Basic usage:
1432     ///
1433     /// ```
1434     /// #![feature(offset_to)]
1435     ///
1436     /// fn main() {
1437     ///     let mut a = [0; 5];
1438     ///     let ptr1: *mut i32 = &mut a[1];
1439     ///     let ptr2: *mut i32 = &mut a[3];
1440     ///     assert_eq!(ptr1.offset_to(ptr2), Some(2));
1441     ///     assert_eq!(ptr2.offset_to(ptr1), Some(-2));
1442     ///     assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
1443     ///     assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
1444     /// }
1445     /// ```
1446     #[unstable(feature = "offset_to", issue = "41079")]
1447     #[inline]
1448     pub fn offset_to(self, other: *const T) -> Option<isize> where T: Sized {
1449         let size = mem::size_of::<T>();
1450         if size == 0 {
1451             None
1452         } else {
1453             let diff = (other as isize).wrapping_sub(self as isize);
1454             Some(diff / size as isize)
1455         }
1456     }
1457
1458     /// Calculates the distance between two pointers. The returned value is in
1459     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1460     ///
1461     /// This function is the inverse of [`offset`].
1462     ///
1463     /// [`offset`]: #method.offset-1
1464     /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
1465     ///
1466     /// # Safety
1467     ///
1468     /// If any of the following conditions are violated, the result is Undefined
1469     /// Behavior:
1470     ///
1471     /// * Both the starting and other pointer must be either in bounds or one
1472     ///   byte past the end of the same allocated object.
1473     ///
1474     /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1475     ///
1476     /// * The distance between the pointers, in bytes, must be an exact multiple
1477     ///   of the size of `T` and `T` must not be a Zero-Sized Type ("ZST").
1478     ///
1479     /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1480     ///
1481     /// The compiler and standard library generally try to ensure allocations
1482     /// never reach a size where an offset is a concern. For instance, `Vec`
1483     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1484     /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1485     ///
1486     /// Most platforms fundamentally can't even construct such an allocation.
1487     /// For instance, no known 64-bit platform can ever serve a request
1488     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1489     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1490     /// more than `isize::MAX` bytes with things like Physical Address
1491     /// Extension. As such, memory acquired directly from allocators or memory
1492     /// mapped files *may* be too large to handle with this function.
1493     ///
1494     /// Consider using [`wrapping_offset_from`] instead if these constraints are
1495     /// difficult to satisfy. The only advantage of this method is that it
1496     /// enables more aggressive compiler optimizations.
1497     ///
1498     /// # Examples
1499     ///
1500     /// Basic usage:
1501     ///
1502     /// ```
1503     /// #![feature(ptr_offset_from)]
1504     ///
1505     /// let a = [0; 5];
1506     /// let ptr1: *mut i32 = &mut a[1];
1507     /// let ptr2: *mut i32 = &mut a[3];
1508     /// unsafe {
1509     ///     assert_eq!(ptr2.offset_from(ptr1), 2);
1510     ///     assert_eq!(ptr1.offset_from(ptr2), -2);
1511     ///     assert_eq!(ptr1.offset(2), ptr2);
1512     ///     assert_eq!(ptr2.offset(-2), ptr1);
1513     /// }
1514     /// ```
1515     #[unstable(feature = "ptr_offset_from", issue = "41079")]
1516     #[inline]
1517     pub unsafe fn offset_from(self, other: *const T) -> isize where T: Sized {
1518         (self as *const T).offset_from(other)
1519     }
1520
1521     /// Calculates the distance between two pointers. The returned value is in
1522     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1523     ///
1524     /// If the address different between the two pointers is not a multiple of
1525     /// `mem::size_of::<T>()` then the result of the division is rounded towards
1526     /// zero.
1527     ///
1528     /// # Panics
1529     ///
1530     /// This function panics if `T` is a zero-sized typed.
1531     ///
1532     /// # Examples
1533     ///
1534     /// Basic usage:
1535     ///
1536     /// ```
1537     /// #![feature(ptr_wrapping_offset_from)]
1538     ///
1539     /// let a = [0; 5];
1540     /// let ptr1: *mut i32 = &mut a[1];
1541     /// let ptr2: *mut i32 = &mut a[3];
1542     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1543     /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1544     /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1545     /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1546     ///
1547     /// let ptr1: *mut i32 = 3 as _;
1548     /// let ptr2: *mut i32 = 13 as _;
1549     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1550     /// ```
1551     #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1552     #[inline]
1553     pub fn wrapping_offset_from(self, other: *const T) -> isize where T: Sized {
1554         (self as *const T).wrapping_offset_from(other)
1555     }
1556
1557     /// Computes the byte offset that needs to be applied in order to
1558     /// make the pointer aligned to `align`.
1559     /// If it is not possible to align the pointer, the implementation returns
1560     /// `usize::max_value()`.
1561     ///
1562     /// There are no guarantees whatsover that offsetting the pointer will not
1563     /// overflow or go beyond the allocation that the pointer points into.
1564     /// It is up to the caller to ensure that the returned offset is correct
1565     /// in all terms other than alignment.
1566     ///
1567     /// # Examples
1568     ///
1569     /// Accessing adjacent `u8` as `u16`
1570     ///
1571     /// ```
1572     /// # #![feature(align_offset)]
1573     /// # fn foo(n: usize) {
1574     /// # use std::mem::align_of;
1575     /// # unsafe {
1576     /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1577     /// let ptr = &x[n] as *const u8;
1578     /// let offset = ptr.align_offset(align_of::<u16>());
1579     /// if offset < x.len() - n - 1 {
1580     ///     let u16_ptr = ptr.offset(offset as isize) as *const u16;
1581     ///     assert_ne!(*u16_ptr, 500);
1582     /// } else {
1583     ///     // while the pointer can be aligned via `offset`, it would point
1584     ///     // outside the allocation
1585     /// }
1586     /// # } }
1587     /// ```
1588     #[unstable(feature = "align_offset", issue = "44488")]
1589     pub fn align_offset(self, align: usize) -> usize {
1590         unsafe {
1591             intrinsics::align_offset(self as *const _, align)
1592         }
1593     }
1594
1595     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1596     ///
1597     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1598     /// offset of `3 * size_of::<T>()` bytes.
1599     ///
1600     /// # Safety
1601     ///
1602     /// If any of the following conditions are violated, the result is Undefined
1603     /// Behavior:
1604     ///
1605     /// * Both the starting and resulting pointer must be either in bounds or one
1606     ///   byte past the end of an allocated object.
1607     ///
1608     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1609     ///
1610     /// * The offset being in bounds cannot rely on "wrapping around" the address
1611     ///   space. That is, the infinite-precision sum must fit in a `usize`.
1612     ///
1613     /// The compiler and standard library generally tries to ensure allocations
1614     /// never reach a size where an offset is a concern. For instance, `Vec`
1615     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1616     /// `vec.as_ptr().add(vec.len())` is always safe.
1617     ///
1618     /// Most platforms fundamentally can't even construct such an allocation.
1619     /// For instance, no known 64-bit platform can ever serve a request
1620     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1621     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1622     /// more than `isize::MAX` bytes with things like Physical Address
1623     /// Extension. As such, memory acquired directly from allocators or memory
1624     /// mapped files *may* be too large to handle with this function.
1625     ///
1626     /// Consider using `wrapping_offset` instead if these constraints are
1627     /// difficult to satisfy. The only advantage of this method is that it
1628     /// enables more aggressive compiler optimizations.
1629     ///
1630     /// # Examples
1631     ///
1632     /// Basic usage:
1633     ///
1634     /// ```
1635     /// let s: &str = "123";
1636     /// let ptr: *const u8 = s.as_ptr();
1637     ///
1638     /// unsafe {
1639     ///     println!("{}", *ptr.add(1) as char);
1640     ///     println!("{}", *ptr.add(2) as char);
1641     /// }
1642     /// ```
1643     #[stable(feature = "pointer_methods", since = "1.26.0")]
1644     #[inline]
1645     pub unsafe fn add(self, count: usize) -> Self
1646         where T: Sized,
1647     {
1648         self.offset(count as isize)
1649     }
1650
1651     /// Calculates the offset from a pointer (convenience for
1652     /// `.offset((count as isize).wrapping_neg())`).
1653     ///
1654     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1655     /// offset of `3 * size_of::<T>()` bytes.
1656     ///
1657     /// # Safety
1658     ///
1659     /// If any of the following conditions are violated, the result is Undefined
1660     /// Behavior:
1661     ///
1662     /// * Both the starting and resulting pointer must be either in bounds or one
1663     ///   byte past the end of an allocated object.
1664     ///
1665     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1666     ///
1667     /// * The offset being in bounds cannot rely on "wrapping around" the address
1668     ///   space. That is, the infinite-precision sum must fit in a usize.
1669     ///
1670     /// The compiler and standard library generally tries to ensure allocations
1671     /// never reach a size where an offset is a concern. For instance, `Vec`
1672     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1673     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1674     ///
1675     /// Most platforms fundamentally can't even construct such an allocation.
1676     /// For instance, no known 64-bit platform can ever serve a request
1677     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1678     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1679     /// more than `isize::MAX` bytes with things like Physical Address
1680     /// Extension. As such, memory acquired directly from allocators or memory
1681     /// mapped files *may* be too large to handle with this function.
1682     ///
1683     /// Consider using `wrapping_offset` instead if these constraints are
1684     /// difficult to satisfy. The only advantage of this method is that it
1685     /// enables more aggressive compiler optimizations.
1686     ///
1687     /// # Examples
1688     ///
1689     /// Basic usage:
1690     ///
1691     /// ```
1692     /// let s: &str = "123";
1693     ///
1694     /// unsafe {
1695     ///     let end: *const u8 = s.as_ptr().add(3);
1696     ///     println!("{}", *end.sub(1) as char);
1697     ///     println!("{}", *end.sub(2) as char);
1698     /// }
1699     /// ```
1700     #[stable(feature = "pointer_methods", since = "1.26.0")]
1701     #[inline]
1702     pub unsafe fn sub(self, count: usize) -> Self
1703         where T: Sized,
1704     {
1705         self.offset((count as isize).wrapping_neg())
1706     }
1707
1708     /// Calculates the offset from a pointer using wrapping arithmetic.
1709     /// (convenience for `.wrapping_offset(count as isize)`)
1710     ///
1711     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1712     /// offset of `3 * size_of::<T>()` bytes.
1713     ///
1714     /// # Safety
1715     ///
1716     /// The resulting pointer does not need to be in bounds, but it is
1717     /// potentially hazardous to dereference (which requires `unsafe`).
1718     ///
1719     /// Always use `.add(count)` instead when possible, because `add`
1720     /// allows the compiler to optimize better.
1721     ///
1722     /// # Examples
1723     ///
1724     /// Basic usage:
1725     ///
1726     /// ```
1727     /// // Iterate using a raw pointer in increments of two elements
1728     /// let data = [1u8, 2, 3, 4, 5];
1729     /// let mut ptr: *const u8 = data.as_ptr();
1730     /// let step = 2;
1731     /// let end_rounded_up = ptr.wrapping_add(6);
1732     ///
1733     /// // This loop prints "1, 3, 5, "
1734     /// while ptr != end_rounded_up {
1735     ///     unsafe {
1736     ///         print!("{}, ", *ptr);
1737     ///     }
1738     ///     ptr = ptr.wrapping_add(step);
1739     /// }
1740     /// ```
1741     #[stable(feature = "pointer_methods", since = "1.26.0")]
1742     #[inline]
1743     pub fn wrapping_add(self, count: usize) -> Self
1744         where T: Sized,
1745     {
1746         self.wrapping_offset(count as isize)
1747     }
1748
1749     /// Calculates the offset from a pointer using wrapping arithmetic.
1750     /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1751     ///
1752     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1753     /// offset of `3 * size_of::<T>()` bytes.
1754     ///
1755     /// # Safety
1756     ///
1757     /// The resulting pointer does not need to be in bounds, but it is
1758     /// potentially hazardous to dereference (which requires `unsafe`).
1759     ///
1760     /// Always use `.sub(count)` instead when possible, because `sub`
1761     /// allows the compiler to optimize better.
1762     ///
1763     /// # Examples
1764     ///
1765     /// Basic usage:
1766     ///
1767     /// ```
1768     /// // Iterate using a raw pointer in increments of two elements (backwards)
1769     /// let data = [1u8, 2, 3, 4, 5];
1770     /// let mut ptr: *const u8 = data.as_ptr();
1771     /// let start_rounded_down = ptr.wrapping_sub(2);
1772     /// ptr = ptr.wrapping_add(4);
1773     /// let step = 2;
1774     /// // This loop prints "5, 3, 1, "
1775     /// while ptr != start_rounded_down {
1776     ///     unsafe {
1777     ///         print!("{}, ", *ptr);
1778     ///     }
1779     ///     ptr = ptr.wrapping_sub(step);
1780     /// }
1781     /// ```
1782     #[stable(feature = "pointer_methods", since = "1.26.0")]
1783     #[inline]
1784     pub fn wrapping_sub(self, count: usize) -> Self
1785         where T: Sized,
1786     {
1787         self.wrapping_offset((count as isize).wrapping_neg())
1788     }
1789
1790     /// Reads the value from `self` without moving it. This leaves the
1791     /// memory in `self` unchanged.
1792     ///
1793     /// # Safety
1794     ///
1795     /// Beyond accepting a raw pointer, this is unsafe because it semantically
1796     /// moves the value out of `self` without preventing further usage of `self`.
1797     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1798     /// `self` is not used before the data is overwritten again (e.g. with `write`,
1799     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1800     /// because it will attempt to drop the value previously at `*self`.
1801     ///
1802     /// The pointer must be aligned; use `read_unaligned` if that is not the case.
1803     ///
1804     /// # Examples
1805     ///
1806     /// Basic usage:
1807     ///
1808     /// ```
1809     /// let x = 12;
1810     /// let y = &x as *const i32;
1811     ///
1812     /// unsafe {
1813     ///     assert_eq!(y.read(), 12);
1814     /// }
1815     /// ```
1816     #[stable(feature = "pointer_methods", since = "1.26.0")]
1817     #[inline]
1818     pub unsafe fn read(self) -> T
1819         where T: Sized,
1820     {
1821         read(self)
1822     }
1823
1824     /// Performs a volatile read of the value from `self` without moving it. This
1825     /// leaves the memory in `self` unchanged.
1826     ///
1827     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1828     /// to not be elided or reordered by the compiler across other volatile
1829     /// operations.
1830     ///
1831     /// # Notes
1832     ///
1833     /// Rust does not currently have a rigorously and formally defined memory model,
1834     /// so the precise semantics of what "volatile" means here is subject to change
1835     /// over time. That being said, the semantics will almost always end up pretty
1836     /// similar to [C11's definition of volatile][c11].
1837     ///
1838     /// The compiler shouldn't change the relative order or number of volatile
1839     /// memory operations. However, volatile memory operations on zero-sized types
1840     /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
1841     /// and may be ignored.
1842     ///
1843     /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1844     ///
1845     /// # Safety
1846     ///
1847     /// Beyond accepting a raw pointer, this is unsafe because it semantically
1848     /// moves the value out of `self` without preventing further usage of `self`.
1849     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1850     /// `self` is not used before the data is overwritten again (e.g. with `write`,
1851     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1852     /// because it will attempt to drop the value previously at `*self`.
1853     ///
1854     /// # Examples
1855     ///
1856     /// Basic usage:
1857     ///
1858     /// ```
1859     /// let x = 12;
1860     /// let y = &x as *const i32;
1861     ///
1862     /// unsafe {
1863     ///     assert_eq!(y.read_volatile(), 12);
1864     /// }
1865     /// ```
1866     #[stable(feature = "pointer_methods", since = "1.26.0")]
1867     #[inline]
1868     pub unsafe fn read_volatile(self) -> T
1869         where T: Sized,
1870     {
1871         read_volatile(self)
1872     }
1873
1874     /// Reads the value from `self` without moving it. This leaves the
1875     /// memory in `self` unchanged.
1876     ///
1877     /// Unlike `read`, the pointer may be unaligned.
1878     ///
1879     /// # Safety
1880     ///
1881     /// Beyond accepting a raw pointer, this is unsafe because it semantically
1882     /// moves the value out of `self` without preventing further usage of `self`.
1883     /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1884     /// `self` is not used before the data is overwritten again (e.g. with `write`,
1885     /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1886     /// because it will attempt to drop the value previously at `*self`.
1887     ///
1888     /// # Examples
1889     ///
1890     /// Basic usage:
1891     ///
1892     /// ```
1893     /// let x = 12;
1894     /// let y = &x as *const i32;
1895     ///
1896     /// unsafe {
1897     ///     assert_eq!(y.read_unaligned(), 12);
1898     /// }
1899     /// ```
1900     #[stable(feature = "pointer_methods", since = "1.26.0")]
1901     #[inline]
1902     pub unsafe fn read_unaligned(self) -> T
1903         where T: Sized,
1904     {
1905         read_unaligned(self)
1906     }
1907
1908     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1909     /// and destination may overlap.
1910     ///
1911     /// NOTE: this has the *same* argument order as `ptr::copy`.
1912     ///
1913     /// This is semantically equivalent to C's `memmove`.
1914     ///
1915     /// # Safety
1916     ///
1917     /// Care must be taken with the ownership of `self` and `dest`.
1918     /// This method semantically moves the values of `self` into `dest`.
1919     /// However it does not drop the contents of `self`, or prevent the contents
1920     /// of `dest` from being dropped or used.
1921     ///
1922     /// # Examples
1923     ///
1924     /// Efficiently create a Rust vector from an unsafe buffer:
1925     ///
1926     /// ```
1927     /// # #[allow(dead_code)]
1928     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1929     ///     let mut dst = Vec::with_capacity(elts);
1930     ///     dst.set_len(elts);
1931     ///     ptr.copy_to(dst.as_mut_ptr(), elts);
1932     ///     dst
1933     /// }
1934     /// ```
1935     #[stable(feature = "pointer_methods", since = "1.26.0")]
1936     #[inline]
1937     pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1938         where T: Sized,
1939     {
1940         copy(self, dest, count)
1941     }
1942
1943     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1944     /// and destination may *not* overlap.
1945     ///
1946     /// NOTE: this has the *same* argument order as `ptr::copy_nonoverlapping`.
1947     ///
1948     /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
1949     ///
1950     /// # Safety
1951     ///
1952     /// Beyond requiring that the program must be allowed to access both regions
1953     /// of memory, it is Undefined Behavior for source and destination to
1954     /// overlap. Care must also be taken with the ownership of `self` and
1955     /// `self`. This method semantically moves the values of `self` into `dest`.
1956     /// However it does not drop the contents of `dest`, or prevent the contents
1957     /// of `self` from being dropped or used.
1958     ///
1959     /// # Examples
1960     ///
1961     /// Efficiently create a Rust vector from an unsafe buffer:
1962     ///
1963     /// ```
1964     /// # #[allow(dead_code)]
1965     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1966     ///     let mut dst = Vec::with_capacity(elts);
1967     ///     dst.set_len(elts);
1968     ///     ptr.copy_to_nonoverlapping(dst.as_mut_ptr(), elts);
1969     ///     dst
1970     /// }
1971     /// ```
1972     #[stable(feature = "pointer_methods", since = "1.26.0")]
1973     #[inline]
1974     pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1975         where T: Sized,
1976     {
1977         copy_nonoverlapping(self, dest, count)
1978     }
1979
1980     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1981     /// and destination may overlap.
1982     ///
1983     /// NOTE: this has the *opposite* argument order of `ptr::copy`.
1984     ///
1985     /// This is semantically equivalent to C's `memmove`.
1986     ///
1987     /// # Safety
1988     ///
1989     /// Care must be taken with the ownership of `src` and `self`.
1990     /// This method semantically moves the values of `src` into `self`.
1991     /// However it does not drop the contents of `self`, or prevent the contents
1992     /// of `src` from being dropped or used.
1993     ///
1994     /// # Examples
1995     ///
1996     /// Efficiently create a Rust vector from an unsafe buffer:
1997     ///
1998     /// ```
1999     /// # #[allow(dead_code)]
2000     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
2001     ///     let mut dst: Vec<T> = Vec::with_capacity(elts);
2002     ///     dst.set_len(elts);
2003     ///     dst.as_mut_ptr().copy_from(ptr, elts);
2004     ///     dst
2005     /// }
2006     /// ```
2007     #[stable(feature = "pointer_methods", since = "1.26.0")]
2008     #[inline]
2009     pub unsafe fn copy_from(self, src: *const T, count: usize)
2010         where T: Sized,
2011     {
2012         copy(src, self, count)
2013     }
2014
2015     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2016     /// and destination may *not* overlap.
2017     ///
2018     /// NOTE: this has the *opposite* argument order of `ptr::copy_nonoverlapping`.
2019     ///
2020     /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
2021     ///
2022     /// # Safety
2023     ///
2024     /// Beyond requiring that the program must be allowed to access both regions
2025     /// of memory, it is Undefined Behavior for source and destination to
2026     /// overlap. Care must also be taken with the ownership of `src` and
2027     /// `self`. This method semantically moves the values of `src` into `self`.
2028     /// However it does not drop the contents of `self`, or prevent the contents
2029     /// of `src` from being dropped or used.
2030     ///
2031     /// # Examples
2032     ///
2033     /// Efficiently create a Rust vector from an unsafe buffer:
2034     ///
2035     /// ```
2036     /// # #[allow(dead_code)]
2037     /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
2038     ///     let mut dst: Vec<T> = Vec::with_capacity(elts);
2039     ///     dst.set_len(elts);
2040     ///     dst.as_mut_ptr().copy_from_nonoverlapping(ptr, elts);
2041     ///     dst
2042     /// }
2043     /// ```
2044     #[stable(feature = "pointer_methods", since = "1.26.0")]
2045     #[inline]
2046     pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
2047         where T: Sized,
2048     {
2049         copy_nonoverlapping(src, self, count)
2050     }
2051
2052     /// Executes the destructor (if any) of the pointed-to value.
2053     ///
2054     /// This has two use cases:
2055     ///
2056     /// * It is *required* to use `drop_in_place` to drop unsized types like
2057     ///   trait objects, because they can't be read out onto the stack and
2058     ///   dropped normally.
2059     ///
2060     /// * It is friendlier to the optimizer to do this over `ptr::read` when
2061     ///   dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
2062     ///   as the compiler doesn't need to prove that it's sound to elide the
2063     ///   copy.
2064     ///
2065     /// # Safety
2066     ///
2067     /// This has all the same safety problems as `ptr::read` with respect to
2068     /// invalid pointers, types, and double drops.
2069     #[stable(feature = "pointer_methods", since = "1.26.0")]
2070     #[inline]
2071     pub unsafe fn drop_in_place(self) {
2072         drop_in_place(self)
2073     }
2074
2075     /// Overwrites a memory location with the given value without reading or
2076     /// dropping the old value.
2077     ///
2078     /// # Safety
2079     ///
2080     /// This operation is marked unsafe because it writes through a raw pointer.
2081     ///
2082     /// It does not drop the contents of `self`. This is safe, but it could leak
2083     /// allocations or resources, so care must be taken not to overwrite an object
2084     /// that should be dropped.
2085     ///
2086     /// Additionally, it does not drop `val`. Semantically, `val` is moved into the
2087     /// location pointed to by `self`.
2088     ///
2089     /// This is appropriate for initializing uninitialized memory, or overwriting
2090     /// memory that has previously been `read` from.
2091     ///
2092     /// The pointer must be aligned; use `write_unaligned` if that is not the case.
2093     ///
2094     /// # Examples
2095     ///
2096     /// Basic usage:
2097     ///
2098     /// ```
2099     /// let mut x = 0;
2100     /// let y = &mut x as *mut i32;
2101     /// let z = 12;
2102     ///
2103     /// unsafe {
2104     ///     y.write(z);
2105     ///     assert_eq!(y.read(), 12);
2106     /// }
2107     /// ```
2108     #[stable(feature = "pointer_methods", since = "1.26.0")]
2109     #[inline]
2110     pub unsafe fn write(self, val: T)
2111         where T: Sized,
2112     {
2113         write(self, val)
2114     }
2115
2116     /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
2117     /// bytes of memory starting at `self` to `val`.
2118     ///
2119     /// # Examples
2120     ///
2121     /// ```
2122     /// let mut vec = vec![0; 4];
2123     /// unsafe {
2124     ///     let vec_ptr = vec.as_mut_ptr();
2125     ///     vec_ptr.write_bytes(b'a', 2);
2126     /// }
2127     /// assert_eq!(vec, [b'a', b'a', 0, 0]);
2128     /// ```
2129     #[stable(feature = "pointer_methods", since = "1.26.0")]
2130     #[inline]
2131     pub unsafe fn write_bytes(self, val: u8, count: usize)
2132         where T: Sized,
2133     {
2134         write_bytes(self, val, count)
2135     }
2136
2137     /// Performs a volatile write of a memory location with the given value without
2138     /// reading or dropping the old value.
2139     ///
2140     /// Volatile operations are intended to act on I/O memory, and are guaranteed
2141     /// to not be elided or reordered by the compiler across other volatile
2142     /// operations.
2143     ///
2144     /// # Notes
2145     ///
2146     /// Rust does not currently have a rigorously and formally defined memory model,
2147     /// so the precise semantics of what "volatile" means here is subject to change
2148     /// over time. That being said, the semantics will almost always end up pretty
2149     /// similar to [C11's definition of volatile][c11].
2150     ///
2151     /// The compiler shouldn't change the relative order or number of volatile
2152     /// memory operations. However, volatile memory operations on zero-sized types
2153     /// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops
2154     /// and may be ignored.
2155     ///
2156     /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
2157     ///
2158     /// # Safety
2159     ///
2160     /// This operation is marked unsafe because it accepts a raw pointer.
2161     ///
2162     /// It does not drop the contents of `self`. This is safe, but it could leak
2163     /// allocations or resources, so care must be taken not to overwrite an object
2164     /// that should be dropped.
2165     ///
2166     /// This is appropriate for initializing uninitialized memory, or overwriting
2167     /// memory that has previously been `read` from.
2168     ///
2169     /// # Examples
2170     ///
2171     /// Basic usage:
2172     ///
2173     /// ```
2174     /// let mut x = 0;
2175     /// let y = &mut x as *mut i32;
2176     /// let z = 12;
2177     ///
2178     /// unsafe {
2179     ///     y.write_volatile(z);
2180     ///     assert_eq!(y.read_volatile(), 12);
2181     /// }
2182     /// ```
2183     #[stable(feature = "pointer_methods", since = "1.26.0")]
2184     #[inline]
2185     pub unsafe fn write_volatile(self, val: T)
2186         where T: Sized,
2187     {
2188         write_volatile(self, val)
2189     }
2190
2191     /// Overwrites a memory location with the given value without reading or
2192     /// dropping the old value.
2193     ///
2194     /// Unlike `write`, the pointer may be unaligned.
2195     ///
2196     /// # Safety
2197     ///
2198     /// This operation is marked unsafe because it writes through a raw pointer.
2199     ///
2200     /// It does not drop the contents of `self`. This is safe, but it could leak
2201     /// allocations or resources, so care must be taken not to overwrite an object
2202     /// that should be dropped.
2203     ///
2204     /// Additionally, it does not drop `self`. Semantically, `self` is moved into the
2205     /// location pointed to by `val`.
2206     ///
2207     /// This is appropriate for initializing uninitialized memory, or overwriting
2208     /// memory that has previously been `read` from.
2209     ///
2210     /// # Examples
2211     ///
2212     /// Basic usage:
2213     ///
2214     /// ```
2215     /// let mut x = 0;
2216     /// let y = &mut x as *mut i32;
2217     /// let z = 12;
2218     ///
2219     /// unsafe {
2220     ///     y.write_unaligned(z);
2221     ///     assert_eq!(y.read_unaligned(), 12);
2222     /// }
2223     /// ```
2224     #[stable(feature = "pointer_methods", since = "1.26.0")]
2225     #[inline]
2226     pub unsafe fn write_unaligned(self, val: T)
2227         where T: Sized,
2228     {
2229         write_unaligned(self, val)
2230     }
2231
2232     /// Replaces the value at `self` with `src`, returning the old
2233     /// value, without dropping either.
2234     ///
2235     /// # Safety
2236     ///
2237     /// This is only unsafe because it accepts a raw pointer.
2238     /// Otherwise, this operation is identical to `mem::replace`.
2239     #[stable(feature = "pointer_methods", since = "1.26.0")]
2240     #[inline]
2241     pub unsafe fn replace(self, src: T) -> T
2242         where T: Sized,
2243     {
2244         replace(self, src)
2245     }
2246
2247     /// Swaps the values at two mutable locations of the same type, without
2248     /// deinitializing either. They may overlap, unlike `mem::swap` which is
2249     /// otherwise equivalent.
2250     ///
2251     /// # Safety
2252     ///
2253     /// This function copies the memory through the raw pointers passed to it
2254     /// as arguments.
2255     ///
2256     /// Ensure that these pointers are valid before calling `swap`.
2257     #[stable(feature = "pointer_methods", since = "1.26.0")]
2258     #[inline]
2259     pub unsafe fn swap(self, with: *mut T)
2260         where T: Sized,
2261     {
2262         swap(self, with)
2263     }
2264 }
2265
2266 // Equality for pointers
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 impl<T: ?Sized> PartialEq for *const T {
2269     #[inline]
2270     fn eq(&self, other: &*const T) -> bool { *self == *other }
2271 }
2272
2273 #[stable(feature = "rust1", since = "1.0.0")]
2274 impl<T: ?Sized> Eq for *const T {}
2275
2276 #[stable(feature = "rust1", since = "1.0.0")]
2277 impl<T: ?Sized> PartialEq for *mut T {
2278     #[inline]
2279     fn eq(&self, other: &*mut T) -> bool { *self == *other }
2280 }
2281
2282 #[stable(feature = "rust1", since = "1.0.0")]
2283 impl<T: ?Sized> Eq for *mut T {}
2284
2285 /// Compare raw pointers for equality.
2286 ///
2287 /// This is the same as using the `==` operator, but less generic:
2288 /// the arguments have to be `*const T` raw pointers,
2289 /// not anything that implements `PartialEq`.
2290 ///
2291 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2292 /// by their address rather than comparing the values they point to
2293 /// (which is what the `PartialEq for &T` implementation does).
2294 ///
2295 /// # Examples
2296 ///
2297 /// ```
2298 /// use std::ptr;
2299 ///
2300 /// let five = 5;
2301 /// let other_five = 5;
2302 /// let five_ref = &five;
2303 /// let same_five_ref = &five;
2304 /// let other_five_ref = &other_five;
2305 ///
2306 /// assert!(five_ref == same_five_ref);
2307 /// assert!(five_ref == other_five_ref);
2308 ///
2309 /// assert!(ptr::eq(five_ref, same_five_ref));
2310 /// assert!(!ptr::eq(five_ref, other_five_ref));
2311 /// ```
2312 #[stable(feature = "ptr_eq", since = "1.17.0")]
2313 #[inline]
2314 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2315     a == b
2316 }
2317
2318 // Impls for function pointers
2319 macro_rules! fnptr_impls_safety_abi {
2320     ($FnTy: ty, $($Arg: ident),*) => {
2321         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2322         impl<Ret, $($Arg),*> PartialEq for $FnTy {
2323             #[inline]
2324             fn eq(&self, other: &Self) -> bool {
2325                 *self as usize == *other as usize
2326             }
2327         }
2328
2329         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2330         impl<Ret, $($Arg),*> Eq for $FnTy {}
2331
2332         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2333         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2334             #[inline]
2335             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2336                 (*self as usize).partial_cmp(&(*other as usize))
2337             }
2338         }
2339
2340         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2341         impl<Ret, $($Arg),*> Ord for $FnTy {
2342             #[inline]
2343             fn cmp(&self, other: &Self) -> Ordering {
2344                 (*self as usize).cmp(&(*other as usize))
2345             }
2346         }
2347
2348         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2349         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2350             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2351                 state.write_usize(*self as usize)
2352             }
2353         }
2354
2355         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2356         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2357             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2358                 fmt::Pointer::fmt(&(*self as *const ()), f)
2359             }
2360         }
2361
2362         #[stable(feature = "fnptr_impls", since = "1.4.0")]
2363         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2364             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2365                 fmt::Pointer::fmt(&(*self as *const ()), f)
2366             }
2367         }
2368     }
2369 }
2370
2371 macro_rules! fnptr_impls_args {
2372     ($($Arg: ident),+) => {
2373         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2374         fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2375         fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2376         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2377         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2378         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2379     };
2380     () => {
2381         // No variadic functions with 0 parameters
2382         fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2383         fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2384         fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2385         fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2386     };
2387 }
2388
2389 fnptr_impls_args! { }
2390 fnptr_impls_args! { A }
2391 fnptr_impls_args! { A, B }
2392 fnptr_impls_args! { A, B, C }
2393 fnptr_impls_args! { A, B, C, D }
2394 fnptr_impls_args! { A, B, C, D, E }
2395 fnptr_impls_args! { A, B, C, D, E, F }
2396 fnptr_impls_args! { A, B, C, D, E, F, G }
2397 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2398 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2399 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2400 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2401 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2402
2403 // Comparison for pointers
2404 #[stable(feature = "rust1", since = "1.0.0")]
2405 impl<T: ?Sized> Ord for *const T {
2406     #[inline]
2407     fn cmp(&self, other: &*const T) -> Ordering {
2408         if self < other {
2409             Less
2410         } else if self == other {
2411             Equal
2412         } else {
2413             Greater
2414         }
2415     }
2416 }
2417
2418 #[stable(feature = "rust1", since = "1.0.0")]
2419 impl<T: ?Sized> PartialOrd for *const T {
2420     #[inline]
2421     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2422         Some(self.cmp(other))
2423     }
2424
2425     #[inline]
2426     fn lt(&self, other: &*const T) -> bool { *self < *other }
2427
2428     #[inline]
2429     fn le(&self, other: &*const T) -> bool { *self <= *other }
2430
2431     #[inline]
2432     fn gt(&self, other: &*const T) -> bool { *self > *other }
2433
2434     #[inline]
2435     fn ge(&self, other: &*const T) -> bool { *self >= *other }
2436 }
2437
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 impl<T: ?Sized> Ord for *mut T {
2440     #[inline]
2441     fn cmp(&self, other: &*mut T) -> Ordering {
2442         if self < other {
2443             Less
2444         } else if self == other {
2445             Equal
2446         } else {
2447             Greater
2448         }
2449     }
2450 }
2451
2452 #[stable(feature = "rust1", since = "1.0.0")]
2453 impl<T: ?Sized> PartialOrd for *mut T {
2454     #[inline]
2455     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2456         Some(self.cmp(other))
2457     }
2458
2459     #[inline]
2460     fn lt(&self, other: &*mut T) -> bool { *self < *other }
2461
2462     #[inline]
2463     fn le(&self, other: &*mut T) -> bool { *self <= *other }
2464
2465     #[inline]
2466     fn gt(&self, other: &*mut T) -> bool { *self > *other }
2467
2468     #[inline]
2469     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
2470 }
2471
2472 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
2473 /// of this wrapper owns the referent. Useful for building abstractions like
2474 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
2475 ///
2476 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
2477 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
2478 /// the kind of strong aliasing guarantees an instance of `T` can expect:
2479 /// the referent of the pointer should not be modified without a unique path to
2480 /// its owning Unique.
2481 ///
2482 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
2483 /// consider using `NonNull`, which has weaker semantics.
2484 ///
2485 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2486 /// is never dereferenced. This is so that enums may use this forbidden value
2487 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
2488 /// However the pointer may still dangle if it isn't dereferenced.
2489 ///
2490 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
2491 /// for any type which upholds Unique's aliasing requirements.
2492 #[unstable(feature = "ptr_internals", issue = "0",
2493            reason = "use NonNull instead and consider PhantomData<T> \
2494                      (if you also use #[may_dangle]), Send, and/or Sync")]
2495 pub struct Unique<T: ?Sized> {
2496     pointer: NonZero<*const T>,
2497     // NOTE: this marker has no consequences for variance, but is necessary
2498     // for dropck to understand that we logically own a `T`.
2499     //
2500     // For details, see:
2501     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
2502     _marker: PhantomData<T>,
2503 }
2504
2505 #[unstable(feature = "ptr_internals", issue = "0")]
2506 impl<T: ?Sized> fmt::Debug for Unique<T> {
2507     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2508         fmt::Pointer::fmt(&self.as_ptr(), f)
2509     }
2510 }
2511
2512 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
2513 /// reference is unaliased. Note that this aliasing invariant is
2514 /// unenforced by the type system; the abstraction using the
2515 /// `Unique` must enforce it.
2516 #[unstable(feature = "ptr_internals", issue = "0")]
2517 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
2518
2519 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
2520 /// reference is unaliased. Note that this aliasing invariant is
2521 /// unenforced by the type system; the abstraction using the
2522 /// `Unique` must enforce it.
2523 #[unstable(feature = "ptr_internals", issue = "0")]
2524 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
2525
2526 #[unstable(feature = "ptr_internals", issue = "0")]
2527 impl<T: Sized> Unique<T> {
2528     /// Creates a new `Unique` that is dangling, but well-aligned.
2529     ///
2530     /// This is useful for initializing types which lazily allocate, like
2531     /// `Vec::new` does.
2532     // FIXME: rename to dangling() to match NonNull?
2533     pub fn empty() -> Self {
2534         unsafe {
2535             let ptr = mem::align_of::<T>() as *mut T;
2536             Unique::new_unchecked(ptr)
2537         }
2538     }
2539 }
2540
2541 #[unstable(feature = "ptr_internals", issue = "0")]
2542 impl<T: ?Sized> Unique<T> {
2543     /// Creates a new `Unique`.
2544     ///
2545     /// # Safety
2546     ///
2547     /// `ptr` must be non-null.
2548     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2549         Unique { pointer: NonZero::new_unchecked(ptr), _marker: PhantomData }
2550     }
2551
2552     /// Creates a new `Unique` if `ptr` is non-null.
2553     pub fn new(ptr: *mut T) -> Option<Self> {
2554         NonZero::new(ptr as *const T).map(|nz| Unique { pointer: nz, _marker: PhantomData })
2555     }
2556
2557     /// Acquires the underlying `*mut` pointer.
2558     pub fn as_ptr(self) -> *mut T {
2559         self.pointer.get() as *mut T
2560     }
2561
2562     /// Dereferences the content.
2563     ///
2564     /// The resulting lifetime is bound to self so this behaves "as if"
2565     /// it were actually an instance of T that is getting borrowed. If a longer
2566     /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2567     pub unsafe fn as_ref(&self) -> &T {
2568         &*self.as_ptr()
2569     }
2570
2571     /// Mutably dereferences the content.
2572     ///
2573     /// The resulting lifetime is bound to self so this behaves "as if"
2574     /// it were actually an instance of T that is getting borrowed. If a longer
2575     /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2576     pub unsafe fn as_mut(&mut self) -> &mut T {
2577         &mut *self.as_ptr()
2578     }
2579 }
2580
2581 #[unstable(feature = "ptr_internals", issue = "0")]
2582 impl<T: ?Sized> Clone for Unique<T> {
2583     fn clone(&self) -> Self {
2584         *self
2585     }
2586 }
2587
2588 #[unstable(feature = "ptr_internals", issue = "0")]
2589 impl<T: ?Sized> Copy for Unique<T> { }
2590
2591 #[unstable(feature = "ptr_internals", issue = "0")]
2592 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
2593
2594 #[unstable(feature = "ptr_internals", issue = "0")]
2595 impl<T: ?Sized> fmt::Pointer for Unique<T> {
2596     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2597         fmt::Pointer::fmt(&self.as_ptr(), f)
2598     }
2599 }
2600
2601 #[unstable(feature = "ptr_internals", issue = "0")]
2602 impl<'a, T: ?Sized> From<&'a mut T> for Unique<T> {
2603     fn from(reference: &'a mut T) -> Self {
2604         Unique { pointer: NonZero::from(reference), _marker: PhantomData }
2605     }
2606 }
2607
2608 #[unstable(feature = "ptr_internals", issue = "0")]
2609 impl<'a, T: ?Sized> From<&'a T> for Unique<T> {
2610     fn from(reference: &'a T) -> Self {
2611         Unique { pointer: NonZero::from(reference), _marker: PhantomData }
2612     }
2613 }
2614
2615 #[unstable(feature = "ptr_internals", issue = "0")]
2616 impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
2617     fn from(p: NonNull<T>) -> Self {
2618         Unique { pointer: p.pointer, _marker: PhantomData }
2619     }
2620 }
2621
2622 /// Previous name of `NonNull`.
2623 #[rustc_deprecated(since = "1.25.0", reason = "renamed to `NonNull`")]
2624 #[unstable(feature = "shared", issue = "27730")]
2625 pub type Shared<T> = NonNull<T>;
2626
2627 /// `*mut T` but non-zero and covariant.
2628 ///
2629 /// This is often the correct thing to use when building data structures using
2630 /// raw pointers, but is ultimately more dangerous to use because of its additional
2631 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
2632 ///
2633 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2634 /// is never dereferenced. This is so that enums may use this forbidden value
2635 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `NonNull<T>`.
2636 /// However the pointer may still dangle if it isn't dereferenced.
2637 ///
2638 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
2639 /// for your use case, you should include some PhantomData in your type to
2640 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
2641 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
2642 /// such as Box, Rc, Arc, Vec, and LinkedList. This is the case because they
2643 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
2644 #[stable(feature = "nonnull", since = "1.25.0")]
2645 pub struct NonNull<T: ?Sized> {
2646     pointer: NonZero<*const T>,
2647 }
2648
2649 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
2650 // NB: This impl is unnecessary, but should provide better error messages.
2651 #[stable(feature = "nonnull", since = "1.25.0")]
2652 impl<T: ?Sized> !Send for NonNull<T> { }
2653
2654 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
2655 // NB: This impl is unnecessary, but should provide better error messages.
2656 #[stable(feature = "nonnull", since = "1.25.0")]
2657 impl<T: ?Sized> !Sync for NonNull<T> { }
2658
2659 impl<T: Sized> NonNull<T> {
2660     /// Creates a new `NonNull` that is dangling, but well-aligned.
2661     ///
2662     /// This is useful for initializing types which lazily allocate, like
2663     /// `Vec::new` does.
2664     #[stable(feature = "nonnull", since = "1.25.0")]
2665     pub fn dangling() -> Self {
2666         unsafe {
2667             let ptr = mem::align_of::<T>() as *mut T;
2668             NonNull::new_unchecked(ptr)
2669         }
2670     }
2671 }
2672
2673 impl<T: ?Sized> NonNull<T> {
2674     /// Creates a new `NonNull`.
2675     ///
2676     /// # Safety
2677     ///
2678     /// `ptr` must be non-null.
2679     #[stable(feature = "nonnull", since = "1.25.0")]
2680     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2681         NonNull { pointer: NonZero::new_unchecked(ptr) }
2682     }
2683
2684     /// Creates a new `NonNull` if `ptr` is non-null.
2685     #[stable(feature = "nonnull", since = "1.25.0")]
2686     pub fn new(ptr: *mut T) -> Option<Self> {
2687         NonZero::new(ptr as *const T).map(|nz| NonNull { pointer: nz })
2688     }
2689
2690     /// Acquires the underlying `*mut` pointer.
2691     #[stable(feature = "nonnull", since = "1.25.0")]
2692     pub fn as_ptr(self) -> *mut T {
2693         self.pointer.get() as *mut T
2694     }
2695
2696     /// Dereferences the content.
2697     ///
2698     /// The resulting lifetime is bound to self so this behaves "as if"
2699     /// it were actually an instance of T that is getting borrowed. If a longer
2700     /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2701     #[stable(feature = "nonnull", since = "1.25.0")]
2702     pub unsafe fn as_ref(&self) -> &T {
2703         &*self.as_ptr()
2704     }
2705
2706     /// Mutably dereferences the content.
2707     ///
2708     /// The resulting lifetime is bound to self so this behaves "as if"
2709     /// it were actually an instance of T that is getting borrowed. If a longer
2710     /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2711     #[stable(feature = "nonnull", since = "1.25.0")]
2712     pub unsafe fn as_mut(&mut self) -> &mut T {
2713         &mut *self.as_ptr()
2714     }
2715
2716     /// Cast to a pointer of another type
2717     #[unstable(feature = "nonnull_cast", issue = "47653")]
2718     pub fn cast<U>(self) -> NonNull<U> {
2719         unsafe {
2720             NonNull::new_unchecked(self.as_ptr() as *mut U)
2721         }
2722     }
2723 }
2724
2725 #[stable(feature = "nonnull", since = "1.25.0")]
2726 impl<T: ?Sized> Clone for NonNull<T> {
2727     fn clone(&self) -> Self {
2728         *self
2729     }
2730 }
2731
2732 #[stable(feature = "nonnull", since = "1.25.0")]
2733 impl<T: ?Sized> Copy for NonNull<T> { }
2734
2735 #[unstable(feature = "coerce_unsized", issue = "27732")]
2736 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
2737
2738 #[stable(feature = "nonnull", since = "1.25.0")]
2739 impl<T: ?Sized> fmt::Debug for NonNull<T> {
2740     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2741         fmt::Pointer::fmt(&self.as_ptr(), f)
2742     }
2743 }
2744
2745 #[stable(feature = "nonnull", since = "1.25.0")]
2746 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
2747     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2748         fmt::Pointer::fmt(&self.as_ptr(), f)
2749     }
2750 }
2751
2752 #[stable(feature = "nonnull", since = "1.25.0")]
2753 impl<T: ?Sized> Eq for NonNull<T> {}
2754
2755 #[stable(feature = "nonnull", since = "1.25.0")]
2756 impl<T: ?Sized> PartialEq for NonNull<T> {
2757     fn eq(&self, other: &Self) -> bool {
2758         self.as_ptr() == other.as_ptr()
2759     }
2760 }
2761
2762 #[stable(feature = "nonnull", since = "1.25.0")]
2763 impl<T: ?Sized> Ord for NonNull<T> {
2764     fn cmp(&self, other: &Self) -> Ordering {
2765         self.as_ptr().cmp(&other.as_ptr())
2766     }
2767 }
2768
2769 #[stable(feature = "nonnull", since = "1.25.0")]
2770 impl<T: ?Sized> PartialOrd for NonNull<T> {
2771     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2772         self.as_ptr().partial_cmp(&other.as_ptr())
2773     }
2774 }
2775
2776 #[stable(feature = "nonnull", since = "1.25.0")]
2777 impl<T: ?Sized> hash::Hash for NonNull<T> {
2778     fn hash<H: hash::Hasher>(&self, state: &mut H) {
2779         self.as_ptr().hash(state)
2780     }
2781 }
2782
2783 #[unstable(feature = "ptr_internals", issue = "0")]
2784 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
2785     fn from(unique: Unique<T>) -> Self {
2786         NonNull { pointer: unique.pointer }
2787     }
2788 }
2789
2790 #[stable(feature = "nonnull", since = "1.25.0")]
2791 impl<'a, T: ?Sized> From<&'a mut T> for NonNull<T> {
2792     fn from(reference: &'a mut T) -> Self {
2793         NonNull { pointer: NonZero::from(reference) }
2794     }
2795 }
2796
2797 #[stable(feature = "nonnull", since = "1.25.0")]
2798 impl<'a, T: ?Sized> From<&'a T> for NonNull<T> {
2799     fn from(reference: &'a T) -> Self {
2800         NonNull { pointer: NonZero::from(reference) }
2801     }
2802 }