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"]
59 #[allow(unconditional_recursion)]
60 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
61 // Code here does not matter - this is replaced by the
62 // real drop glue by the compiler.
63 drop_in_place(to_drop);
66 /// Creates a null raw pointer.
73 /// let p: *const i32 = ptr::null();
74 /// assert!(p.is_null());
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub const fn null<T>() -> *const T { 0 as *const T }
80 /// Creates a null mutable raw pointer.
87 /// let p: *mut i32 = ptr::null_mut();
88 /// assert!(p.is_null());
91 #[stable(feature = "rust1", since = "1.0.0")]
92 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
94 /// Swaps the values at two mutable locations of the same type, without
95 /// deinitializing either. They may overlap, unlike `mem::swap` which is
96 /// otherwise equivalent.
100 /// This function copies the memory through the raw pointers passed to it
103 /// Ensure that these pointers are valid before calling `swap`.
105 #[stable(feature = "rust1", since = "1.0.0")]
106 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
107 // Give ourselves some scratch space to work with
108 let mut tmp: T = mem::uninitialized();
111 copy_nonoverlapping(x, &mut tmp, 1);
112 copy(y, x, 1); // `x` and `y` may overlap
113 copy_nonoverlapping(&tmp, y, 1);
115 // y and t now point to the same thing, but we need to completely forget `tmp`
116 // because it's no longer relevant.
120 /// Replaces the value at `dest` with `src`, returning the old
121 /// value, without dropping either.
125 /// This is only unsafe because it accepts a raw pointer.
126 /// Otherwise, this operation is identical to `mem::replace`.
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
130 mem::swap(&mut *dest, &mut src); // cannot overlap
134 /// Reads the value from `src` without moving it. This leaves the
135 /// memory in `src` unchanged.
139 /// Beyond accepting a raw pointer, this is unsafe because it semantically
140 /// moves the value out of `src` without preventing further usage of `src`.
141 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
142 /// `src` is not used before the data is overwritten again (e.g. with `write`,
143 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
144 /// because it will attempt to drop the value previously at `*src`.
146 /// The pointer must be aligned; use `read_unaligned` if that is not the case.
154 /// let y = &x as *const i32;
157 /// assert_eq!(std::ptr::read(y), 12);
161 #[stable(feature = "rust1", since = "1.0.0")]
162 pub unsafe fn read<T>(src: *const T) -> T {
163 let mut tmp: T = mem::uninitialized();
164 copy_nonoverlapping(src, &mut tmp, 1);
168 /// Reads the value from `src` without moving it. This leaves the
169 /// memory in `src` unchanged.
171 /// Unlike `read`, the pointer may be unaligned.
175 /// Beyond accepting a raw pointer, this is unsafe because it semantically
176 /// moves the value out of `src` without preventing further usage of `src`.
177 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
178 /// `src` is not used before the data is overwritten again (e.g. with `write`,
179 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
180 /// because it will attempt to drop the value previously at `*src`.
188 /// let y = &x as *const i32;
191 /// assert_eq!(std::ptr::read_unaligned(y), 12);
195 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
196 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
197 let mut tmp: T = mem::uninitialized();
198 copy_nonoverlapping(src as *const u8,
199 &mut tmp as *mut T as *mut u8,
200 mem::size_of::<T>());
204 /// Overwrites a memory location with the given value without reading or
205 /// dropping the old value.
209 /// This operation is marked unsafe because it accepts a raw pointer.
211 /// It does not drop the contents of `dst`. This is safe, but it could leak
212 /// allocations or resources, so care must be taken not to overwrite an object
213 /// that should be dropped.
215 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
216 /// location pointed to by `dst`.
218 /// This is appropriate for initializing uninitialized memory, or overwriting
219 /// memory that has previously been `read` from.
221 /// The pointer must be aligned; use `write_unaligned` if that is not the case.
229 /// let y = &mut x as *mut i32;
233 /// std::ptr::write(y, z);
234 /// assert_eq!(std::ptr::read(y), 12);
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub unsafe fn write<T>(dst: *mut T, src: T) {
240 intrinsics::move_val_init(&mut *dst, src)
243 /// Overwrites a memory location with the given value without reading or
244 /// dropping the old value.
246 /// Unlike `write`, the pointer may be unaligned.
250 /// This operation is marked unsafe because it accepts a raw pointer.
252 /// It does not drop the contents of `dst`. This is safe, but it could leak
253 /// allocations or resources, so care must be taken not to overwrite an object
254 /// that should be dropped.
256 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
257 /// location pointed to by `dst`.
259 /// This is appropriate for initializing uninitialized memory, or overwriting
260 /// memory that has previously been `read` from.
268 /// let y = &mut x as *mut i32;
272 /// std::ptr::write_unaligned(y, z);
273 /// assert_eq!(std::ptr::read_unaligned(y), 12);
277 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
278 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
279 copy_nonoverlapping(&src as *const T as *const u8,
281 mem::size_of::<T>());
285 /// Performs a volatile read of the value from `src` without moving it. This
286 /// leaves the memory in `src` unchanged.
288 /// Volatile operations are intended to act on I/O memory, and are guaranteed
289 /// to not be elided or reordered by the compiler across other volatile
294 /// Rust does not currently have a rigorously and formally defined memory model,
295 /// so the precise semantics of what "volatile" means here is subject to change
296 /// over time. That being said, the semantics will almost always end up pretty
297 /// similar to [C11's definition of volatile][c11].
299 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
303 /// Beyond accepting a raw pointer, this is unsafe because it semantically
304 /// moves the value out of `src` without preventing further usage of `src`.
305 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
306 /// `src` is not used before the data is overwritten again (e.g. with `write`,
307 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
308 /// because it will attempt to drop the value previously at `*src`.
316 /// let y = &x as *const i32;
319 /// assert_eq!(std::ptr::read_volatile(y), 12);
323 #[stable(feature = "volatile", since = "1.9.0")]
324 pub unsafe fn read_volatile<T>(src: *const T) -> T {
325 intrinsics::volatile_load(src)
328 /// Performs a volatile write of a memory location with the given value without
329 /// reading or dropping the old value.
331 /// Volatile operations are intended to act on I/O memory, and are guaranteed
332 /// to not be elided or reordered by the compiler across other volatile
337 /// Rust does not currently have a rigorously and formally defined memory model,
338 /// so the precise semantics of what "volatile" means here is subject to change
339 /// over time. That being said, the semantics will almost always end up pretty
340 /// similar to [C11's definition of volatile][c11].
342 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
346 /// This operation is marked unsafe because it accepts a raw pointer.
348 /// It does not drop the contents of `dst`. This is safe, but it could leak
349 /// allocations or resources, so care must be taken not to overwrite an object
350 /// that should be dropped.
352 /// This is appropriate for initializing uninitialized memory, or overwriting
353 /// memory that has previously been `read` from.
361 /// let y = &mut x as *mut i32;
365 /// std::ptr::write_volatile(y, z);
366 /// assert_eq!(std::ptr::read_volatile(y), 12);
370 #[stable(feature = "volatile", since = "1.9.0")]
371 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
372 intrinsics::volatile_store(dst, src);
375 #[lang = "const_ptr"]
376 impl<T: ?Sized> *const T {
377 /// Returns `true` if the pointer is null.
384 /// let s: &str = "Follow the rabbit";
385 /// let ptr: *const u8 = s.as_ptr();
386 /// assert!(!ptr.is_null());
388 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn is_null(self) -> bool where T: Sized {
394 /// Returns `None` if the pointer is null, or else returns a reference to
395 /// the value wrapped in `Some`.
399 /// While this method and its mutable counterpart are useful for
400 /// null-safety, it is important to note that this is still an unsafe
401 /// operation because the returned value could be pointing to invalid
404 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
405 /// not necessarily reflect the actual lifetime of the data.
412 /// let val: *const u8 = &10u8 as *const u8;
415 /// if let Some(val_back) = val.as_ref() {
416 /// println!("We got back the value: {}!", val_back);
420 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
422 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
430 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
431 /// `count` of 3 represents a pointer offset of `3 * size_of::<T>()` bytes.
435 /// Both the starting and resulting pointer must be either in bounds or one
436 /// byte past the end of an allocated object. If either pointer is out of
437 /// bounds or arithmetic overflow occurs then
438 /// any further use of the returned value will result in undefined behavior.
445 /// let s: &str = "123";
446 /// let ptr: *const u8 = s.as_ptr();
449 /// println!("{}", *ptr.offset(1) as char);
450 /// println!("{}", *ptr.offset(2) as char);
453 #[stable(feature = "rust1", since = "1.0.0")]
455 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
456 intrinsics::offset(self, count)
459 /// Calculates the offset from a pointer using wrapping arithmetic.
460 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
461 /// offset of `3 * size_of::<T>()` bytes.
465 /// The resulting pointer does not need to be in bounds, but it is
466 /// potentially hazardous to dereference (which requires `unsafe`).
468 /// Always use `.offset(count)` instead when possible, because `offset`
469 /// allows the compiler to optimize better.
476 /// // Iterate using a raw pointer in increments of two elements
477 /// let data = [1u8, 2, 3, 4, 5];
478 /// let mut ptr: *const u8 = data.as_ptr();
480 /// let end_rounded_up = ptr.wrapping_offset(6);
482 /// // This loop prints "1, 3, 5, "
483 /// while ptr != end_rounded_up {
485 /// print!("{}, ", *ptr);
487 /// ptr = ptr.wrapping_offset(step);
490 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
492 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
494 intrinsics::arith_offset(self, count)
498 /// Calculates the distance between two pointers. The returned value is in
499 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
501 /// If the address different between the two pointers ia not a multiple of
502 /// `mem::size_of::<T>()` then the result of the division is rounded towards
505 /// This function returns `None` if `T` is a zero-sized typed.
512 /// #![feature(offset_to)]
516 /// let ptr1: *const i32 = &a[1];
517 /// let ptr2: *const i32 = &a[3];
518 /// assert_eq!(ptr1.offset_to(ptr2), Some(2));
519 /// assert_eq!(ptr2.offset_to(ptr1), Some(-2));
520 /// assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
521 /// assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
524 #[unstable(feature = "offset_to", issue = "41079")]
526 pub fn offset_to(self, other: *const T) -> Option<isize> where T: Sized {
527 let size = mem::size_of::<T>();
531 let diff = (other as isize).wrapping_sub(self as isize);
532 Some(diff / size as isize)
538 impl<T: ?Sized> *mut T {
539 /// Returns `true` if the pointer is null.
546 /// let mut s = [1, 2, 3];
547 /// let ptr: *mut u32 = s.as_mut_ptr();
548 /// assert!(!ptr.is_null());
550 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn is_null(self) -> bool where T: Sized {
556 /// Returns `None` if the pointer is null, or else returns a reference to
557 /// the value wrapped in `Some`.
561 /// While this method and its mutable counterpart are useful for
562 /// null-safety, it is important to note that this is still an unsafe
563 /// operation because the returned value could be pointing to invalid
566 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
567 /// not necessarily reflect the actual lifetime of the data.
574 /// let val: *mut u8 = &mut 10u8 as *mut u8;
577 /// if let Some(val_back) = val.as_ref() {
578 /// println!("We got back the value: {}!", val_back);
582 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
584 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
592 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
593 /// `count` of 3 represents a pointer offset of `3 * size_of::<T>()` bytes.
597 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
598 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
599 /// the pointer is used.
606 /// let mut s = [1, 2, 3];
607 /// let ptr: *mut u32 = s.as_mut_ptr();
610 /// println!("{}", *ptr.offset(1));
611 /// println!("{}", *ptr.offset(2));
614 #[stable(feature = "rust1", since = "1.0.0")]
616 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
617 intrinsics::offset(self, count) as *mut T
620 /// Calculates the offset from a pointer using wrapping arithmetic.
621 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
622 /// offset of `3 * size_of::<T>()` bytes.
626 /// The resulting pointer does not need to be in bounds, but it is
627 /// potentially hazardous to dereference (which requires `unsafe`).
629 /// Always use `.offset(count)` instead when possible, because `offset`
630 /// allows the compiler to optimize better.
637 /// // Iterate using a raw pointer in increments of two elements
638 /// let mut data = [1u8, 2, 3, 4, 5];
639 /// let mut ptr: *mut u8 = data.as_mut_ptr();
641 /// let end_rounded_up = ptr.wrapping_offset(6);
643 /// while ptr != end_rounded_up {
647 /// ptr = ptr.wrapping_offset(step);
649 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
651 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
653 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
655 intrinsics::arith_offset(self, count) as *mut T
659 /// Returns `None` if the pointer is null, or else returns a mutable
660 /// reference to the value wrapped in `Some`.
664 /// As with `as_ref`, this is unsafe because it cannot verify the validity
665 /// of the returned pointer, nor can it ensure that the lifetime `'a`
666 /// returned is indeed a valid lifetime for the contained data.
673 /// let mut s = [1, 2, 3];
674 /// let ptr: *mut u32 = s.as_mut_ptr();
675 /// let first_value = unsafe { ptr.as_mut().unwrap() };
676 /// *first_value = 4;
677 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
679 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
681 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
689 /// Calculates the distance between two pointers. The returned value is in
690 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
692 /// If the address different between the two pointers ia not a multiple of
693 /// `mem::size_of::<T>()` then the result of the division is rounded towards
696 /// This function returns `None` if `T` is a zero-sized typed.
703 /// #![feature(offset_to)]
706 /// let mut a = [0; 5];
707 /// let ptr1: *mut i32 = &mut a[1];
708 /// let ptr2: *mut i32 = &mut a[3];
709 /// assert_eq!(ptr1.offset_to(ptr2), Some(2));
710 /// assert_eq!(ptr2.offset_to(ptr1), Some(-2));
711 /// assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
712 /// assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
715 #[unstable(feature = "offset_to", issue = "41079")]
717 pub fn offset_to(self, other: *const T) -> Option<isize> where T: Sized {
718 let size = mem::size_of::<T>();
722 let diff = (other as isize).wrapping_sub(self as isize);
723 Some(diff / size as isize)
728 // Equality for pointers
729 #[stable(feature = "rust1", since = "1.0.0")]
730 impl<T: ?Sized> PartialEq for *const T {
732 fn eq(&self, other: &*const T) -> bool { *self == *other }
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl<T: ?Sized> Eq for *const T {}
738 #[stable(feature = "rust1", since = "1.0.0")]
739 impl<T: ?Sized> PartialEq for *mut T {
741 fn eq(&self, other: &*mut T) -> bool { *self == *other }
744 #[stable(feature = "rust1", since = "1.0.0")]
745 impl<T: ?Sized> Eq for *mut T {}
747 /// Compare raw pointers for equality.
749 /// This is the same as using the `==` operator, but less generic:
750 /// the arguments have to be `*const T` raw pointers,
751 /// not anything that implements `PartialEq`.
753 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
754 /// by their address rather than comparing the values they point to
755 /// (which is what the `PartialEq for &T` implementation does).
763 /// let other_five = 5;
764 /// let five_ref = &five;
765 /// let same_five_ref = &five;
766 /// let other_five_ref = &other_five;
768 /// assert!(five_ref == same_five_ref);
769 /// assert!(five_ref == other_five_ref);
771 /// assert!(ptr::eq(five_ref, same_five_ref));
772 /// assert!(!ptr::eq(five_ref, other_five_ref));
774 #[stable(feature = "ptr_eq", since = "1.17.0")]
776 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
780 #[stable(feature = "rust1", since = "1.0.0")]
781 impl<T: ?Sized> Clone for *const T {
783 fn clone(&self) -> *const T {
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl<T: ?Sized> Clone for *mut T {
791 fn clone(&self) -> *mut T {
796 // Impls for function pointers
797 macro_rules! fnptr_impls_safety_abi {
798 ($FnTy: ty, $($Arg: ident),*) => {
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl<Ret, $($Arg),*> Clone for $FnTy {
802 fn clone(&self) -> Self {
807 #[stable(feature = "fnptr_impls", since = "1.4.0")]
808 impl<Ret, $($Arg),*> PartialEq for $FnTy {
810 fn eq(&self, other: &Self) -> bool {
811 *self as usize == *other as usize
815 #[stable(feature = "fnptr_impls", since = "1.4.0")]
816 impl<Ret, $($Arg),*> Eq for $FnTy {}
818 #[stable(feature = "fnptr_impls", since = "1.4.0")]
819 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
821 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
822 (*self as usize).partial_cmp(&(*other as usize))
826 #[stable(feature = "fnptr_impls", since = "1.4.0")]
827 impl<Ret, $($Arg),*> Ord for $FnTy {
829 fn cmp(&self, other: &Self) -> Ordering {
830 (*self as usize).cmp(&(*other as usize))
834 #[stable(feature = "fnptr_impls", since = "1.4.0")]
835 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
836 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
837 state.write_usize(*self as usize)
841 #[stable(feature = "fnptr_impls", since = "1.4.0")]
842 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
843 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
844 fmt::Pointer::fmt(&(*self as *const ()), f)
848 #[stable(feature = "fnptr_impls", since = "1.4.0")]
849 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
850 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
851 fmt::Pointer::fmt(&(*self as *const ()), f)
857 macro_rules! fnptr_impls_args {
858 ($($Arg: ident),+) => {
859 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
860 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
861 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
862 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
863 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
864 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
867 // No variadic functions with 0 parameters
868 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
869 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
870 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
871 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
875 fnptr_impls_args! { }
876 fnptr_impls_args! { A }
877 fnptr_impls_args! { A, B }
878 fnptr_impls_args! { A, B, C }
879 fnptr_impls_args! { A, B, C, D }
880 fnptr_impls_args! { A, B, C, D, E }
881 fnptr_impls_args! { A, B, C, D, E, F }
882 fnptr_impls_args! { A, B, C, D, E, F, G }
883 fnptr_impls_args! { A, B, C, D, E, F, G, H }
884 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
885 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
886 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
887 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
889 // Comparison for pointers
890 #[stable(feature = "rust1", since = "1.0.0")]
891 impl<T: ?Sized> Ord for *const T {
893 fn cmp(&self, other: &*const T) -> Ordering {
896 } else if self == other {
904 #[stable(feature = "rust1", since = "1.0.0")]
905 impl<T: ?Sized> PartialOrd for *const T {
907 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
908 Some(self.cmp(other))
912 fn lt(&self, other: &*const T) -> bool { *self < *other }
915 fn le(&self, other: &*const T) -> bool { *self <= *other }
918 fn gt(&self, other: &*const T) -> bool { *self > *other }
921 fn ge(&self, other: &*const T) -> bool { *self >= *other }
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl<T: ?Sized> Ord for *mut T {
927 fn cmp(&self, other: &*mut T) -> Ordering {
930 } else if self == other {
938 #[stable(feature = "rust1", since = "1.0.0")]
939 impl<T: ?Sized> PartialOrd for *mut T {
941 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
942 Some(self.cmp(other))
946 fn lt(&self, other: &*mut T) -> bool { *self < *other }
949 fn le(&self, other: &*mut T) -> bool { *self <= *other }
952 fn gt(&self, other: &*mut T) -> bool { *self > *other }
955 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
958 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
959 /// of this wrapper owns the referent. Useful for building abstractions like
960 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
962 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
963 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
964 /// the kind of strong aliasing guarantees an instance of `T` can expect:
965 /// the referent of the pointer should not be modified without a unique path to
966 /// its owning Unique.
968 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
969 /// consider using `Shared`, which has weaker semantics.
971 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
972 /// is never dereferenced. This is so that enums may use this forbidden value
973 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
974 /// However the pointer may still dangle if it isn't dereferenced.
976 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
977 /// for any type which upholds Unique's aliasing requirements.
978 #[allow(missing_debug_implementations)]
979 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
981 pub struct Unique<T: ?Sized> {
982 pointer: NonZero<*const T>,
983 // NOTE: this marker has no consequences for variance, but is necessary
984 // for dropck to understand that we logically own a `T`.
987 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
988 _marker: PhantomData<T>,
991 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
992 /// reference is unaliased. Note that this aliasing invariant is
993 /// unenforced by the type system; the abstraction using the
994 /// `Unique` must enforce it.
995 #[unstable(feature = "unique", issue = "27730")]
996 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
998 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
999 /// reference is unaliased. Note that this aliasing invariant is
1000 /// unenforced by the type system; the abstraction using the
1001 /// `Unique` must enforce it.
1002 #[unstable(feature = "unique", issue = "27730")]
1003 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
1005 #[unstable(feature = "unique", issue = "27730")]
1006 impl<T: Sized> Unique<T> {
1007 /// Creates a new `Unique` that is dangling, but well-aligned.
1009 /// This is useful for initializing types which lazily allocate, like
1010 /// `Vec::new` does.
1011 pub fn empty() -> Self {
1013 let ptr = mem::align_of::<T>() as *mut T;
1019 #[unstable(feature = "unique", issue = "27730")]
1020 impl<T: ?Sized> Unique<T> {
1021 /// Creates a new `Unique`.
1025 /// `ptr` must be non-null.
1026 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
1027 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
1030 /// Acquires the underlying `*mut` pointer.
1031 pub fn as_ptr(self) -> *mut T {
1032 self.pointer.get() as *mut T
1035 /// Dereferences the content.
1037 /// The resulting lifetime is bound to self so this behaves "as if"
1038 /// it were actually an instance of T that is getting borrowed. If a longer
1039 /// (unbound) lifetime is needed, use `&*my_ptr.ptr()`.
1040 pub unsafe fn as_ref(&self) -> &T {
1044 /// Mutably dereferences the content.
1046 /// The resulting lifetime is bound to self so this behaves "as if"
1047 /// it were actually an instance of T that is getting borrowed. If a longer
1048 /// (unbound) lifetime is needed, use `&mut *my_ptr.ptr()`.
1049 pub unsafe fn as_mut(&mut self) -> &mut T {
1054 #[unstable(feature = "shared", issue = "27730")]
1055 impl<T: ?Sized> Clone for Unique<T> {
1056 fn clone(&self) -> Self {
1061 #[unstable(feature = "shared", issue = "27730")]
1062 impl<T: ?Sized> Copy for Unique<T> { }
1064 #[unstable(feature = "unique", issue = "27730")]
1065 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
1067 #[unstable(feature = "unique", issue = "27730")]
1068 impl<T: ?Sized> fmt::Pointer for Unique<T> {
1069 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1070 fmt::Pointer::fmt(&self.as_ptr(), f)
1074 /// A wrapper around a raw `*mut T` that indicates that the possessor
1075 /// of this wrapper has shared ownership of the referent. Useful for
1076 /// building abstractions like `Rc<T>`, `Arc<T>`, or doubly-linked lists, which
1077 /// internally use aliased raw pointers to manage the memory that they own.
1079 /// This is similar to `Unique`, except that it doesn't make any aliasing
1080 /// guarantees, and doesn't derive Send and Sync. Note that unlike `&T`,
1081 /// Shared has no special mutability requirements. Shared may mutate data
1082 /// aliased by other Shared pointers. More precise rules require Rust to
1083 /// develop an actual aliasing model.
1085 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
1086 /// is never dereferenced. This is so that enums may use this forbidden value
1087 /// as a discriminant -- `Option<Shared<T>>` has the same size as `Shared<T>`.
1088 /// However the pointer may still dangle if it isn't dereferenced.
1090 /// Unlike `*mut T`, `Shared<T>` is covariant over `T`. If this is incorrect
1091 /// for your use case, you should include some PhantomData in your type to
1092 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
1093 /// Usually this won't be necessary; covariance is correct for Rc, Arc, and LinkedList
1094 /// because they provide a public API that follows the normal shared XOR mutable
1096 #[allow(missing_debug_implementations)]
1097 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
1099 pub struct Shared<T: ?Sized> {
1100 pointer: NonZero<*const T>,
1101 // NOTE: this marker has no consequences for variance, but is necessary
1102 // for dropck to understand that we logically own a `T`.
1104 // For details, see:
1105 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
1106 _marker: PhantomData<T>,
1109 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
1110 // NB: This impl is unnecessary, but should provide better error messages.
1111 #[unstable(feature = "shared", issue = "27730")]
1112 impl<T: ?Sized> !Send for Shared<T> { }
1114 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
1115 // NB: This impl is unnecessary, but should provide better error messages.
1116 #[unstable(feature = "shared", issue = "27730")]
1117 impl<T: ?Sized> !Sync for Shared<T> { }
1119 #[unstable(feature = "shared", issue = "27730")]
1120 impl<T: Sized> Shared<T> {
1121 /// Creates a new `Shared` that is dangling, but well-aligned.
1123 /// This is useful for initializing types which lazily allocate, like
1124 /// `Vec::new` does.
1125 pub fn empty() -> Self {
1127 let ptr = mem::align_of::<T>() as *mut T;
1133 #[unstable(feature = "shared", issue = "27730")]
1134 impl<T: ?Sized> Shared<T> {
1135 /// Creates a new `Shared`.
1139 /// `ptr` must be non-null.
1140 pub unsafe fn new(ptr: *mut T) -> Self {
1141 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
1144 /// Acquires the underlying `*mut` pointer.
1145 pub fn as_ptr(self) -> *mut T {
1146 self.pointer.get() as *mut T
1149 /// Dereferences the content.
1151 /// The resulting lifetime is bound to self so this behaves "as if"
1152 /// it were actually an instance of T that is getting borrowed. If a longer
1153 /// (unbound) lifetime is needed, use `&*my_ptr.ptr()`.
1154 pub unsafe fn as_ref(&self) -> &T {
1158 /// Mutably dereferences the content.
1160 /// The resulting lifetime is bound to self so this behaves "as if"
1161 /// it were actually an instance of T that is getting borrowed. If a longer
1162 /// (unbound) lifetime is needed, use `&mut *my_ptr.ptr_mut()`.
1163 pub unsafe fn as_mut(&mut self) -> &mut T {
1167 /// Acquires the underlying pointer as a `*mut` pointer.
1168 #[rustc_deprecated(since = "1.19", reason = "renamed to `as_ptr` for ergonomics/consistency")]
1169 #[unstable(feature = "shared", issue = "27730")]
1170 pub unsafe fn as_mut_ptr(&self) -> *mut T {
1175 #[unstable(feature = "shared", issue = "27730")]
1176 impl<T: ?Sized> Clone for Shared<T> {
1177 fn clone(&self) -> Self {
1182 #[unstable(feature = "shared", issue = "27730")]
1183 impl<T: ?Sized> Copy for Shared<T> { }
1185 #[unstable(feature = "shared", issue = "27730")]
1186 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
1188 #[unstable(feature = "shared", issue = "27730")]
1189 impl<T: ?Sized> fmt::Pointer for Shared<T> {
1190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1191 fmt::Pointer::fmt(&self.as_ptr(), f)