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.
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.
11 // FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory
13 //! Raw, unsafe pointers, `*const T`, and `*mut T`.
15 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
17 #![stable(feature = "rust1", since = "1.0.0")]
20 use ops::CoerceUnsized;
23 use marker::{PhantomData, Unsize};
27 use cmp::Ordering::{self, Less, Equal, Greater};
29 // FIXME #19649: intrinsic docs don't render, so these have no docs :(
31 #[stable(feature = "rust1", since = "1.0.0")]
32 pub use intrinsics::copy_nonoverlapping;
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use intrinsics::copy;
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use intrinsics::write_bytes;
40 /// Executes the destructor (if any) of the pointed-to value.
42 /// This has two use cases:
44 /// * It is *required* to use `drop_in_place` to drop unsized types like
45 /// trait objects, because they can't be read out onto the stack and
48 /// * It is friendlier to the optimizer to do this over `ptr::read` when
49 /// dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
50 /// as the compiler doesn't need to prove that it's sound to elide the
53 /// # Undefined Behavior
55 /// This has all the same safety problems as `ptr::read` with respect to
56 /// invalid pointers, types, and double drops.
57 #[stable(feature = "drop_in_place", since = "1.8.0")]
58 #[lang="drop_in_place"]
60 #[allow(unconditional_recursion)]
61 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
62 // Code here does not matter - this is replaced by the
63 // real drop glue by the compiler.
64 drop_in_place(to_drop);
67 /// Creates a null raw pointer.
74 /// let p: *const i32 = ptr::null();
75 /// assert!(p.is_null());
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub const fn null<T>() -> *const T { 0 as *const T }
81 /// Creates a null mutable raw pointer.
88 /// let p: *mut i32 = ptr::null_mut();
89 /// assert!(p.is_null());
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
95 /// Swaps the values at two mutable locations of the same type, without
96 /// deinitializing either. They may overlap, unlike `mem::swap` which is
97 /// otherwise equivalent.
101 /// This function copies the memory through the raw pointers passed to it
104 /// Ensure that these pointers are valid before calling `swap`.
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
108 // Give ourselves some scratch space to work with
109 let mut tmp: T = mem::uninitialized();
112 copy_nonoverlapping(x, &mut tmp, 1);
113 copy(y, x, 1); // `x` and `y` may overlap
114 copy_nonoverlapping(&tmp, y, 1);
116 // y and t now point to the same thing, but we need to completely forget `tmp`
117 // because it's no longer relevant.
121 /// Replaces the value at `dest` with `src`, returning the old
122 /// value, without dropping either.
126 /// This is only unsafe because it accepts a raw pointer.
127 /// Otherwise, this operation is identical to `mem::replace`.
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
131 mem::swap(&mut *dest, &mut src); // cannot overlap
135 /// Reads the value from `src` without moving it. This leaves the
136 /// memory in `src` unchanged.
140 /// Beyond accepting a raw pointer, this is unsafe because it semantically
141 /// moves the value out of `src` without preventing further usage of `src`.
142 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
143 /// `src` is not used before the data is overwritten again (e.g. with `write`,
144 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
145 /// because it will attempt to drop the value previously at `*src`.
147 /// The pointer must be aligned; use `read_unaligned` if that is not the case.
155 /// let y = &x as *const i32;
158 /// assert_eq!(std::ptr::read(y), 12);
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub unsafe fn read<T>(src: *const T) -> T {
164 let mut tmp: T = mem::uninitialized();
165 copy_nonoverlapping(src, &mut tmp, 1);
169 /// Reads the value from `src` without moving it. This leaves the
170 /// memory in `src` unchanged.
172 /// Unlike `read`, the pointer may be unaligned.
176 /// Beyond accepting a raw pointer, this is unsafe because it semantically
177 /// moves the value out of `src` without preventing further usage of `src`.
178 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
179 /// `src` is not used before the data is overwritten again (e.g. with `write`,
180 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
181 /// because it will attempt to drop the value previously at `*src`.
189 /// let y = &x as *const i32;
192 /// assert_eq!(std::ptr::read_unaligned(y), 12);
196 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
197 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
198 let mut tmp: T = mem::uninitialized();
199 copy_nonoverlapping(src as *const u8,
200 &mut tmp as *mut T as *mut u8,
201 mem::size_of::<T>());
205 /// Overwrites a memory location with the given value without reading or
206 /// dropping the old value.
210 /// This operation is marked unsafe because it accepts a raw pointer.
212 /// It does not drop the contents of `dst`. This is safe, but it could leak
213 /// allocations or resources, so care must be taken not to overwrite an object
214 /// that should be dropped.
216 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
217 /// location pointed to by `dst`.
219 /// This is appropriate for initializing uninitialized memory, or overwriting
220 /// memory that has previously been `read` from.
222 /// The pointer must be aligned; use `write_unaligned` if that is not the case.
230 /// let y = &mut x as *mut i32;
234 /// std::ptr::write(y, z);
235 /// assert_eq!(std::ptr::read(y), 12);
239 #[stable(feature = "rust1", since = "1.0.0")]
240 pub unsafe fn write<T>(dst: *mut T, src: T) {
241 intrinsics::move_val_init(&mut *dst, src)
244 /// Overwrites a memory location with the given value without reading or
245 /// dropping the old value.
247 /// Unlike `write`, the pointer may be unaligned.
251 /// This operation is marked unsafe because it accepts a raw pointer.
253 /// It does not drop the contents of `dst`. This is safe, but it could leak
254 /// allocations or resources, so care must be taken not to overwrite an object
255 /// that should be dropped.
257 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
258 /// location pointed to by `dst`.
260 /// This is appropriate for initializing uninitialized memory, or overwriting
261 /// memory that has previously been `read` from.
269 /// let y = &mut x as *mut i32;
273 /// std::ptr::write_unaligned(y, z);
274 /// assert_eq!(std::ptr::read_unaligned(y), 12);
278 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
279 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
280 copy_nonoverlapping(&src as *const T as *const u8,
282 mem::size_of::<T>());
286 /// Performs a volatile read of the value from `src` without moving it. This
287 /// leaves the memory in `src` unchanged.
289 /// Volatile operations are intended to act on I/O memory, and are guaranteed
290 /// to not be elided or reordered by the compiler across other volatile
295 /// Rust does not currently have a rigorously and formally defined memory model,
296 /// so the precise semantics of what "volatile" means here is subject to change
297 /// over time. That being said, the semantics will almost always end up pretty
298 /// similar to [C11's definition of volatile][c11].
300 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
304 /// Beyond accepting a raw pointer, this is unsafe because it semantically
305 /// moves the value out of `src` without preventing further usage of `src`.
306 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
307 /// `src` is not used before the data is overwritten again (e.g. with `write`,
308 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
309 /// because it will attempt to drop the value previously at `*src`.
317 /// let y = &x as *const i32;
320 /// assert_eq!(std::ptr::read_volatile(y), 12);
324 #[stable(feature = "volatile", since = "1.9.0")]
325 pub unsafe fn read_volatile<T>(src: *const T) -> T {
326 intrinsics::volatile_load(src)
329 /// Performs a volatile write of a memory location with the given value without
330 /// reading or dropping the old value.
332 /// Volatile operations are intended to act on I/O memory, and are guaranteed
333 /// to not be elided or reordered by the compiler across other volatile
338 /// Rust does not currently have a rigorously and formally defined memory model,
339 /// so the precise semantics of what "volatile" means here is subject to change
340 /// over time. That being said, the semantics will almost always end up pretty
341 /// similar to [C11's definition of volatile][c11].
343 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
347 /// This operation is marked unsafe because it accepts a raw pointer.
349 /// It does not drop the contents of `dst`. This is safe, but it could leak
350 /// allocations or resources, so care must be taken not to overwrite an object
351 /// that should be dropped.
353 /// This is appropriate for initializing uninitialized memory, or overwriting
354 /// memory that has previously been `read` from.
362 /// let y = &mut x as *mut i32;
366 /// std::ptr::write_volatile(y, z);
367 /// assert_eq!(std::ptr::read_volatile(y), 12);
371 #[stable(feature = "volatile", since = "1.9.0")]
372 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
373 intrinsics::volatile_store(dst, src);
376 #[lang = "const_ptr"]
377 impl<T: ?Sized> *const T {
378 /// Returns `true` if the pointer is null.
385 /// let s: &str = "Follow the rabbit";
386 /// let ptr: *const u8 = s.as_ptr();
387 /// assert!(!ptr.is_null());
389 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn is_null(self) -> bool where T: Sized {
395 /// Returns `None` if the pointer is null, or else returns a reference to
396 /// the value wrapped in `Some`.
400 /// While this method and its mutable counterpart are useful for
401 /// null-safety, it is important to note that this is still an unsafe
402 /// operation because the returned value could be pointing to invalid
405 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
406 /// not necessarily reflect the actual lifetime of the data.
413 /// let val: *const u8 = &10u8 as *const u8;
416 /// if let Some(val_back) = val.as_ref() {
417 /// println!("We got back the value: {}!", val_back);
421 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
423 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
431 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
432 /// `count` of 3 represents a pointer offset of `3 * size_of::<T>()` bytes.
436 /// Both the starting and resulting pointer must be either in bounds or one
437 /// byte past the end of an allocated object. If either pointer is out of
438 /// bounds or arithmetic overflow occurs then
439 /// any further use of the returned value will result in undefined behavior.
446 /// let s: &str = "123";
447 /// let ptr: *const u8 = s.as_ptr();
450 /// println!("{}", *ptr.offset(1) as char);
451 /// println!("{}", *ptr.offset(2) as char);
454 #[stable(feature = "rust1", since = "1.0.0")]
456 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
457 intrinsics::offset(self, count)
460 /// Calculates the offset from a pointer using wrapping arithmetic.
461 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
462 /// offset of `3 * size_of::<T>()` bytes.
466 /// The resulting pointer does not need to be in bounds, but it is
467 /// potentially hazardous to dereference (which requires `unsafe`).
469 /// Always use `.offset(count)` instead when possible, because `offset`
470 /// allows the compiler to optimize better.
477 /// // Iterate using a raw pointer in increments of two elements
478 /// let data = [1u8, 2, 3, 4, 5];
479 /// let mut ptr: *const u8 = data.as_ptr();
481 /// let end_rounded_up = ptr.wrapping_offset(6);
483 /// // This loop prints "1, 3, 5, "
484 /// while ptr != end_rounded_up {
486 /// print!("{}, ", *ptr);
488 /// ptr = ptr.wrapping_offset(step);
491 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
493 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
495 intrinsics::arith_offset(self, count)
499 /// Calculates the distance between two pointers. The returned value is in
500 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
502 /// If the address different between the two pointers ia not a multiple of
503 /// `mem::size_of::<T>()` then the result of the division is rounded towards
506 /// This function returns `None` if `T` is a zero-sized typed.
513 /// #![feature(offset_to)]
517 /// let ptr1: *const i32 = &a[1];
518 /// let ptr2: *const i32 = &a[3];
519 /// assert_eq!(ptr1.offset_to(ptr2), Some(2));
520 /// assert_eq!(ptr2.offset_to(ptr1), Some(-2));
521 /// assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
522 /// assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
525 #[unstable(feature = "offset_to", issue = "41079")]
527 pub fn offset_to(self, other: *const T) -> Option<isize> where T: Sized {
528 let size = mem::size_of::<T>();
532 let diff = (other as isize).wrapping_sub(self as isize);
533 Some(diff / size as isize)
539 impl<T: ?Sized> *mut T {
540 /// Returns `true` if the pointer is null.
547 /// let mut s = [1, 2, 3];
548 /// let ptr: *mut u32 = s.as_mut_ptr();
549 /// assert!(!ptr.is_null());
551 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn is_null(self) -> bool where T: Sized {
557 /// Returns `None` if the pointer is null, or else returns a reference to
558 /// the value wrapped in `Some`.
562 /// While this method and its mutable counterpart are useful for
563 /// null-safety, it is important to note that this is still an unsafe
564 /// operation because the returned value could be pointing to invalid
567 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
568 /// not necessarily reflect the actual lifetime of the data.
575 /// let val: *mut u8 = &mut 10u8 as *mut u8;
578 /// if let Some(val_back) = val.as_ref() {
579 /// println!("We got back the value: {}!", val_back);
583 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
585 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
593 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
594 /// `count` of 3 represents a pointer offset of `3 * size_of::<T>()` bytes.
598 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
599 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
600 /// the pointer is used.
607 /// let mut s = [1, 2, 3];
608 /// let ptr: *mut u32 = s.as_mut_ptr();
611 /// println!("{}", *ptr.offset(1));
612 /// println!("{}", *ptr.offset(2));
615 #[stable(feature = "rust1", since = "1.0.0")]
617 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
618 intrinsics::offset(self, count) as *mut T
621 /// Calculates the offset from a pointer using wrapping arithmetic.
622 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
623 /// offset of `3 * size_of::<T>()` bytes.
627 /// The resulting pointer does not need to be in bounds, but it is
628 /// potentially hazardous to dereference (which requires `unsafe`).
630 /// Always use `.offset(count)` instead when possible, because `offset`
631 /// allows the compiler to optimize better.
638 /// // Iterate using a raw pointer in increments of two elements
639 /// let mut data = [1u8, 2, 3, 4, 5];
640 /// let mut ptr: *mut u8 = data.as_mut_ptr();
642 /// let end_rounded_up = ptr.wrapping_offset(6);
644 /// while ptr != end_rounded_up {
648 /// ptr = ptr.wrapping_offset(step);
650 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
652 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
654 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
656 intrinsics::arith_offset(self, count) as *mut T
660 /// Returns `None` if the pointer is null, or else returns a mutable
661 /// reference to the value wrapped in `Some`.
665 /// As with `as_ref`, this is unsafe because it cannot verify the validity
666 /// of the returned pointer, nor can it ensure that the lifetime `'a`
667 /// returned is indeed a valid lifetime for the contained data.
674 /// let mut s = [1, 2, 3];
675 /// let ptr: *mut u32 = s.as_mut_ptr();
676 /// let first_value = unsafe { ptr.as_mut().unwrap() };
677 /// *first_value = 4;
678 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
680 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
682 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
690 /// Calculates the distance between two pointers. The returned value is in
691 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
693 /// If the address different between the two pointers ia not a multiple of
694 /// `mem::size_of::<T>()` then the result of the division is rounded towards
697 /// This function returns `None` if `T` is a zero-sized typed.
704 /// #![feature(offset_to)]
707 /// let mut a = [0; 5];
708 /// let ptr1: *mut i32 = &mut a[1];
709 /// let ptr2: *mut i32 = &mut a[3];
710 /// assert_eq!(ptr1.offset_to(ptr2), Some(2));
711 /// assert_eq!(ptr2.offset_to(ptr1), Some(-2));
712 /// assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
713 /// assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
716 #[unstable(feature = "offset_to", issue = "41079")]
718 pub fn offset_to(self, other: *const T) -> Option<isize> where T: Sized {
719 let size = mem::size_of::<T>();
723 let diff = (other as isize).wrapping_sub(self as isize);
724 Some(diff / size as isize)
729 // Equality for pointers
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl<T: ?Sized> PartialEq for *const T {
733 fn eq(&self, other: &*const T) -> bool { *self == *other }
736 #[stable(feature = "rust1", since = "1.0.0")]
737 impl<T: ?Sized> Eq for *const T {}
739 #[stable(feature = "rust1", since = "1.0.0")]
740 impl<T: ?Sized> PartialEq for *mut T {
742 fn eq(&self, other: &*mut T) -> bool { *self == *other }
745 #[stable(feature = "rust1", since = "1.0.0")]
746 impl<T: ?Sized> Eq for *mut T {}
748 /// Compare raw pointers for equality.
750 /// This is the same as using the `==` operator, but less generic:
751 /// the arguments have to be `*const T` raw pointers,
752 /// not anything that implements `PartialEq`.
754 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
755 /// by their address rather than comparing the values they point to
756 /// (which is what the `PartialEq for &T` implementation does).
764 /// let other_five = 5;
765 /// let five_ref = &five;
766 /// let same_five_ref = &five;
767 /// let other_five_ref = &other_five;
769 /// assert!(five_ref == same_five_ref);
770 /// assert!(five_ref == other_five_ref);
772 /// assert!(ptr::eq(five_ref, same_five_ref));
773 /// assert!(!ptr::eq(five_ref, other_five_ref));
775 #[stable(feature = "ptr_eq", since = "1.17.0")]
777 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
781 #[stable(feature = "rust1", since = "1.0.0")]
782 impl<T: ?Sized> Clone for *const T {
784 fn clone(&self) -> *const T {
789 #[stable(feature = "rust1", since = "1.0.0")]
790 impl<T: ?Sized> Clone for *mut T {
792 fn clone(&self) -> *mut T {
797 // Impls for function pointers
798 macro_rules! fnptr_impls_safety_abi {
799 ($FnTy: ty, $($Arg: ident),*) => {
800 #[stable(feature = "rust1", since = "1.0.0")]
801 impl<Ret, $($Arg),*> Clone for $FnTy {
803 fn clone(&self) -> Self {
808 #[stable(feature = "fnptr_impls", since = "1.4.0")]
809 impl<Ret, $($Arg),*> PartialEq for $FnTy {
811 fn eq(&self, other: &Self) -> bool {
812 *self as usize == *other as usize
816 #[stable(feature = "fnptr_impls", since = "1.4.0")]
817 impl<Ret, $($Arg),*> Eq for $FnTy {}
819 #[stable(feature = "fnptr_impls", since = "1.4.0")]
820 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
822 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
823 (*self as usize).partial_cmp(&(*other as usize))
827 #[stable(feature = "fnptr_impls", since = "1.4.0")]
828 impl<Ret, $($Arg),*> Ord for $FnTy {
830 fn cmp(&self, other: &Self) -> Ordering {
831 (*self as usize).cmp(&(*other as usize))
835 #[stable(feature = "fnptr_impls", since = "1.4.0")]
836 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
837 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
838 state.write_usize(*self as usize)
842 #[stable(feature = "fnptr_impls", since = "1.4.0")]
843 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
844 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
845 fmt::Pointer::fmt(&(*self as *const ()), f)
849 #[stable(feature = "fnptr_impls", since = "1.4.0")]
850 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
851 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
852 fmt::Pointer::fmt(&(*self as *const ()), f)
858 macro_rules! fnptr_impls_args {
859 ($($Arg: ident),+) => {
860 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
861 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
862 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
863 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
864 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
865 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
868 // No variadic functions with 0 parameters
869 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
870 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
871 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
872 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
876 fnptr_impls_args! { }
877 fnptr_impls_args! { A }
878 fnptr_impls_args! { A, B }
879 fnptr_impls_args! { A, B, C }
880 fnptr_impls_args! { A, B, C, D }
881 fnptr_impls_args! { A, B, C, D, E }
882 fnptr_impls_args! { A, B, C, D, E, F }
883 fnptr_impls_args! { A, B, C, D, E, F, G }
884 fnptr_impls_args! { A, B, C, D, E, F, G, H }
885 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
886 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
887 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
888 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
890 // Comparison for pointers
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl<T: ?Sized> Ord for *const T {
894 fn cmp(&self, other: &*const T) -> Ordering {
897 } else if self == other {
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<T: ?Sized> PartialOrd for *const T {
908 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
909 Some(self.cmp(other))
913 fn lt(&self, other: &*const T) -> bool { *self < *other }
916 fn le(&self, other: &*const T) -> bool { *self <= *other }
919 fn gt(&self, other: &*const T) -> bool { *self > *other }
922 fn ge(&self, other: &*const T) -> bool { *self >= *other }
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<T: ?Sized> Ord for *mut T {
928 fn cmp(&self, other: &*mut T) -> Ordering {
931 } else if self == other {
939 #[stable(feature = "rust1", since = "1.0.0")]
940 impl<T: ?Sized> PartialOrd for *mut T {
942 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
943 Some(self.cmp(other))
947 fn lt(&self, other: &*mut T) -> bool { *self < *other }
950 fn le(&self, other: &*mut T) -> bool { *self <= *other }
953 fn gt(&self, other: &*mut T) -> bool { *self > *other }
956 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
959 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
960 /// of this wrapper owns the referent. Useful for building abstractions like
961 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
963 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
964 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
965 /// the kind of strong aliasing guarantees an instance of `T` can expect:
966 /// the referent of the pointer should not be modified without a unique path to
967 /// its owning Unique.
969 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
970 /// consider using `Shared`, which has weaker semantics.
972 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
973 /// is never dereferenced. This is so that enums may use this forbidden value
974 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
975 /// However the pointer may still dangle if it isn't dereferenced.
977 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
978 /// for any type which upholds Unique's aliasing requirements.
979 #[allow(missing_debug_implementations)]
980 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
982 pub struct Unique<T: ?Sized> {
983 pointer: NonZero<*const T>,
984 // NOTE: this marker has no consequences for variance, but is necessary
985 // for dropck to understand that we logically own a `T`.
988 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
989 _marker: PhantomData<T>,
992 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
993 /// reference is unaliased. Note that this aliasing invariant is
994 /// unenforced by the type system; the abstraction using the
995 /// `Unique` must enforce it.
996 #[unstable(feature = "unique", issue = "27730")]
997 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
999 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
1000 /// reference is unaliased. Note that this aliasing invariant is
1001 /// unenforced by the type system; the abstraction using the
1002 /// `Unique` must enforce it.
1003 #[unstable(feature = "unique", issue = "27730")]
1004 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
1006 #[unstable(feature = "unique", issue = "27730")]
1007 impl<T: Sized> Unique<T> {
1008 /// Creates a new `Unique` that is dangling, but well-aligned.
1010 /// This is useful for initializing types which lazily allocate, like
1011 /// `Vec::new` does.
1012 pub fn empty() -> Self {
1014 let ptr = mem::align_of::<T>() as *mut T;
1020 #[unstable(feature = "unique", issue = "27730")]
1021 impl<T: ?Sized> Unique<T> {
1022 /// Creates a new `Unique`.
1026 /// `ptr` must be non-null.
1027 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
1028 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
1031 /// Acquires the underlying `*mut` pointer.
1032 pub fn as_ptr(self) -> *mut T {
1033 self.pointer.get() as *mut T
1036 /// Dereferences the content.
1038 /// The resulting lifetime is bound to self so this behaves "as if"
1039 /// it were actually an instance of T that is getting borrowed. If a longer
1040 /// (unbound) lifetime is needed, use `&*my_ptr.ptr()`.
1041 pub unsafe fn as_ref(&self) -> &T {
1045 /// Mutably dereferences the content.
1047 /// The resulting lifetime is bound to self so this behaves "as if"
1048 /// it were actually an instance of T that is getting borrowed. If a longer
1049 /// (unbound) lifetime is needed, use `&mut *my_ptr.ptr()`.
1050 pub unsafe fn as_mut(&mut self) -> &mut T {
1055 #[unstable(feature = "shared", issue = "27730")]
1056 impl<T: ?Sized> Clone for Unique<T> {
1057 fn clone(&self) -> Self {
1062 #[unstable(feature = "shared", issue = "27730")]
1063 impl<T: ?Sized> Copy for Unique<T> { }
1065 #[unstable(feature = "unique", issue = "27730")]
1066 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
1068 #[unstable(feature = "unique", issue = "27730")]
1069 impl<T: ?Sized> fmt::Pointer for Unique<T> {
1070 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1071 fmt::Pointer::fmt(&self.as_ptr(), f)
1075 /// A wrapper around a raw `*mut T` that indicates that the possessor
1076 /// of this wrapper has shared ownership of the referent. Useful for
1077 /// building abstractions like `Rc<T>`, `Arc<T>`, or doubly-linked lists, which
1078 /// internally use aliased raw pointers to manage the memory that they own.
1080 /// This is similar to `Unique`, except that it doesn't make any aliasing
1081 /// guarantees, and doesn't derive Send and Sync. Note that unlike `&T`,
1082 /// Shared has no special mutability requirements. Shared may mutate data
1083 /// aliased by other Shared pointers. More precise rules require Rust to
1084 /// develop an actual aliasing model.
1086 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
1087 /// is never dereferenced. This is so that enums may use this forbidden value
1088 /// as a discriminant -- `Option<Shared<T>>` has the same size as `Shared<T>`.
1089 /// However the pointer may still dangle if it isn't dereferenced.
1091 /// Unlike `*mut T`, `Shared<T>` is covariant over `T`. If this is incorrect
1092 /// for your use case, you should include some PhantomData in your type to
1093 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
1094 /// Usually this won't be necessary; covariance is correct for Rc, Arc, and LinkedList
1095 /// because they provide a public API that follows the normal shared XOR mutable
1097 #[allow(missing_debug_implementations)]
1098 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
1100 pub struct Shared<T: ?Sized> {
1101 pointer: NonZero<*const T>,
1102 // NOTE: this marker has no consequences for variance, but is necessary
1103 // for dropck to understand that we logically own a `T`.
1105 // For details, see:
1106 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
1107 _marker: PhantomData<T>,
1110 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
1111 // NB: This impl is unnecessary, but should provide better error messages.
1112 #[unstable(feature = "shared", issue = "27730")]
1113 impl<T: ?Sized> !Send for Shared<T> { }
1115 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
1116 // NB: This impl is unnecessary, but should provide better error messages.
1117 #[unstable(feature = "shared", issue = "27730")]
1118 impl<T: ?Sized> !Sync for Shared<T> { }
1120 #[unstable(feature = "shared", issue = "27730")]
1121 impl<T: Sized> Shared<T> {
1122 /// Creates a new `Shared` that is dangling, but well-aligned.
1124 /// This is useful for initializing types which lazily allocate, like
1125 /// `Vec::new` does.
1126 pub fn empty() -> Self {
1128 let ptr = mem::align_of::<T>() as *mut T;
1134 #[unstable(feature = "shared", issue = "27730")]
1135 impl<T: ?Sized> Shared<T> {
1136 /// Creates a new `Shared`.
1140 /// `ptr` must be non-null.
1141 pub unsafe fn new(ptr: *mut T) -> Self {
1142 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
1145 /// Acquires the underlying `*mut` pointer.
1146 pub fn as_ptr(self) -> *mut T {
1147 self.pointer.get() as *mut T
1150 /// Dereferences the content.
1152 /// The resulting lifetime is bound to self so this behaves "as if"
1153 /// it were actually an instance of T that is getting borrowed. If a longer
1154 /// (unbound) lifetime is needed, use `&*my_ptr.ptr()`.
1155 pub unsafe fn as_ref(&self) -> &T {
1159 /// Mutably dereferences the content.
1161 /// The resulting lifetime is bound to self so this behaves "as if"
1162 /// it were actually an instance of T that is getting borrowed. If a longer
1163 /// (unbound) lifetime is needed, use `&mut *my_ptr.ptr_mut()`.
1164 pub unsafe fn as_mut(&mut self) -> &mut T {
1168 /// Acquires the underlying pointer as a `*mut` pointer.
1169 #[rustc_deprecated(since = "1.19", reason = "renamed to `as_ptr` for ergonomics/consistency")]
1170 #[unstable(feature = "shared", issue = "27730")]
1171 pub unsafe fn as_mut_ptr(&self) -> *mut T {
1176 #[unstable(feature = "shared", issue = "27730")]
1177 impl<T: ?Sized> Clone for Shared<T> {
1178 fn clone(&self) -> Self {
1183 #[unstable(feature = "shared", issue = "27730")]
1184 impl<T: ?Sized> Copy for Shared<T> { }
1186 #[unstable(feature = "shared", issue = "27730")]
1187 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
1189 #[unstable(feature = "shared", issue = "27730")]
1190 impl<T: ?Sized> fmt::Pointer for Shared<T> {
1191 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1192 fmt::Pointer::fmt(&self.as_ptr(), f)