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, Deref};
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 #[stable(feature = "drop_in_place", since = "1.8.0")]
41 pub use intrinsics::drop_in_place;
43 /// Creates a null raw pointer.
50 /// let p: *const i32 = ptr::null();
51 /// assert!(p.is_null());
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub const fn null<T>() -> *const T { 0 as *const T }
57 /// Creates a null mutable raw pointer.
64 /// let p: *mut i32 = ptr::null_mut();
65 /// assert!(p.is_null());
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
71 /// Swaps the values at two mutable locations of the same type, without
72 /// deinitializing either. They may overlap, unlike `mem::swap` which is
73 /// otherwise equivalent.
77 /// This function copies the memory through the raw pointers passed to it
80 /// Ensure that these pointers are valid before calling `swap`.
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
84 // Give ourselves some scratch space to work with
85 let mut tmp: T = mem::uninitialized();
88 copy_nonoverlapping(x, &mut tmp, 1);
89 copy(y, x, 1); // `x` and `y` may overlap
90 copy_nonoverlapping(&tmp, y, 1);
92 // y and t now point to the same thing, but we need to completely forget `tmp`
93 // because it's no longer relevant.
97 /// Replaces the value at `dest` with `src`, returning the old
98 /// value, without dropping either.
102 /// This is only unsafe because it accepts a raw pointer.
103 /// Otherwise, this operation is identical to `mem::replace`.
105 #[stable(feature = "rust1", since = "1.0.0")]
106 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
107 mem::swap(&mut *dest, &mut src); // cannot overlap
111 /// Reads the value from `src` without moving it. This leaves the
112 /// memory in `src` unchanged.
116 /// Beyond accepting a raw pointer, this is unsafe because it semantically
117 /// moves the value out of `src` without preventing further usage of `src`.
118 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
119 /// `src` is not used before the data is overwritten again (e.g. with `write`,
120 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
121 /// because it will attempt to drop the value previously at `*src`.
123 /// The pointer must be aligned; use `read_unaligned` if that is not the case.
131 /// let y = &x as *const i32;
134 /// assert_eq!(std::ptr::read(y), 12);
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub unsafe fn read<T>(src: *const T) -> T {
140 let mut tmp: T = mem::uninitialized();
141 copy_nonoverlapping(src, &mut tmp, 1);
145 /// Reads the value from `src` without moving it. This leaves the
146 /// memory in `src` unchanged.
148 /// Unlike `read`, the pointer may be unaligned.
152 /// Beyond accepting a raw pointer, this is unsafe because it semantically
153 /// moves the value out of `src` without preventing further usage of `src`.
154 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
155 /// `src` is not used before the data is overwritten again (e.g. with `write`,
156 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
157 /// because it will attempt to drop the value previously at `*src`.
165 /// let y = &x as *const i32;
168 /// assert_eq!(std::ptr::read_unaligned(y), 12);
172 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
173 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
174 let mut tmp: T = mem::uninitialized();
175 copy_nonoverlapping(src as *const u8,
176 &mut tmp as *mut T as *mut u8,
177 mem::size_of::<T>());
181 /// Overwrites a memory location with the given value without reading or
182 /// dropping the old value.
186 /// This operation is marked unsafe because it accepts a raw pointer.
188 /// It does not drop the contents of `dst`. This is safe, but it could leak
189 /// allocations or resources, so care must be taken not to overwrite an object
190 /// that should be dropped.
192 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
193 /// location pointed to by `dst`.
195 /// This is appropriate for initializing uninitialized memory, or overwriting
196 /// memory that has previously been `read` from.
198 /// The pointer must be aligned; use `write_unaligned` if that is not the case.
206 /// let y = &mut x as *mut i32;
210 /// std::ptr::write(y, z);
211 /// assert_eq!(std::ptr::read(y), 12);
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub unsafe fn write<T>(dst: *mut T, src: T) {
217 intrinsics::move_val_init(&mut *dst, src)
220 /// Overwrites a memory location with the given value without reading or
221 /// dropping the old value.
223 /// Unlike `write`, the pointer may be unaligned.
227 /// This operation is marked unsafe because it accepts a raw pointer.
229 /// It does not drop the contents of `dst`. This is safe, but it could leak
230 /// allocations or resources, so care must be taken not to overwrite an object
231 /// that should be dropped.
233 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
234 /// location pointed to by `dst`.
236 /// This is appropriate for initializing uninitialized memory, or overwriting
237 /// memory that has previously been `read` from.
245 /// let y = &mut x as *mut i32;
249 /// std::ptr::write_unaligned(y, z);
250 /// assert_eq!(std::ptr::read_unaligned(y), 12);
254 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
255 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
256 copy_nonoverlapping(&src as *const T as *const u8,
258 mem::size_of::<T>());
262 /// Performs a volatile read of the value from `src` without moving it. This
263 /// leaves the memory in `src` unchanged.
265 /// Volatile operations are intended to act on I/O memory, and are guaranteed
266 /// to not be elided or reordered by the compiler across other volatile
271 /// Rust does not currently have a rigorously and formally defined memory model,
272 /// so the precise semantics of what "volatile" means here is subject to change
273 /// over time. That being said, the semantics will almost always end up pretty
274 /// similar to [C11's definition of volatile][c11].
276 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
280 /// Beyond accepting a raw pointer, this is unsafe because it semantically
281 /// moves the value out of `src` without preventing further usage of `src`.
282 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
283 /// `src` is not used before the data is overwritten again (e.g. with `write`,
284 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
285 /// because it will attempt to drop the value previously at `*src`.
293 /// let y = &x as *const i32;
296 /// assert_eq!(std::ptr::read_volatile(y), 12);
300 #[stable(feature = "volatile", since = "1.9.0")]
301 pub unsafe fn read_volatile<T>(src: *const T) -> T {
302 intrinsics::volatile_load(src)
305 /// Performs a volatile write of a memory location with the given value without
306 /// reading or dropping the old value.
308 /// Volatile operations are intended to act on I/O memory, and are guaranteed
309 /// to not be elided or reordered by the compiler across other volatile
314 /// Rust does not currently have a rigorously and formally defined memory model,
315 /// so the precise semantics of what "volatile" means here is subject to change
316 /// over time. That being said, the semantics will almost always end up pretty
317 /// similar to [C11's definition of volatile][c11].
319 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
323 /// This operation is marked unsafe because it accepts a raw pointer.
325 /// It does not drop the contents of `dst`. This is safe, but it could leak
326 /// allocations or resources, so care must be taken not to overwrite an object
327 /// that should be dropped.
329 /// This is appropriate for initializing uninitialized memory, or overwriting
330 /// memory that has previously been `read` from.
338 /// let y = &mut x as *mut i32;
342 /// std::ptr::write_volatile(y, z);
343 /// assert_eq!(std::ptr::read_volatile(y), 12);
347 #[stable(feature = "volatile", since = "1.9.0")]
348 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
349 intrinsics::volatile_store(dst, src);
352 #[lang = "const_ptr"]
353 impl<T: ?Sized> *const T {
354 /// Returns true if the pointer is null.
361 /// let s: &str = "Follow the rabbit";
362 /// let ptr: *const u8 = s.as_ptr();
363 /// assert!(!ptr.is_null());
365 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn is_null(self) -> bool where T: Sized {
371 /// Returns `None` if the pointer is null, or else returns a reference to
372 /// the value wrapped in `Some`.
376 /// While this method and its mutable counterpart are useful for
377 /// null-safety, it is important to note that this is still an unsafe
378 /// operation because the returned value could be pointing to invalid
381 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
382 /// not necessarily reflect the actual lifetime of the data.
389 /// let val: *const u8 = &10u8 as *const u8;
392 /// if let Some(val_back) = val.as_ref() {
393 /// println!("We got back the value: {}!", val_back);
397 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
399 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
407 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
408 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
412 /// Both the starting and resulting pointer must be either in bounds or one
413 /// byte past the end of an allocated object. If either pointer is out of
414 /// bounds or arithmetic overflow occurs then
415 /// any further use of the returned value will result in undefined behavior.
422 /// let s: &str = "123";
423 /// let ptr: *const u8 = s.as_ptr();
426 /// println!("{}", *ptr.offset(1) as char);
427 /// println!("{}", *ptr.offset(2) as char);
430 #[stable(feature = "rust1", since = "1.0.0")]
432 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
433 intrinsics::offset(self, count)
436 /// Calculates the offset from a pointer using wrapping arithmetic.
437 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
438 /// offset of `3 * sizeof::<T>()` bytes.
442 /// The resulting pointer does not need to be in bounds, but it is
443 /// potentially hazardous to dereference (which requires `unsafe`).
445 /// Always use `.offset(count)` instead when possible, because `offset`
446 /// allows the compiler to optimize better.
453 /// // Iterate using a raw pointer in increments of two elements
454 /// let data = [1u8, 2, 3, 4, 5];
455 /// let mut ptr: *const u8 = data.as_ptr();
457 /// let end_rounded_up = ptr.wrapping_offset(6);
459 /// // This loop prints "1, 3, 5, "
460 /// while ptr != end_rounded_up {
462 /// print!("{}, ", *ptr);
464 /// ptr = ptr.wrapping_offset(step);
467 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
469 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
471 intrinsics::arith_offset(self, count)
477 impl<T: ?Sized> *mut T {
478 /// Returns true if the pointer is null.
485 /// let mut s = [1, 2, 3];
486 /// let ptr: *mut u32 = s.as_mut_ptr();
487 /// assert!(!ptr.is_null());
489 #[stable(feature = "rust1", since = "1.0.0")]
491 pub fn is_null(self) -> bool where T: Sized {
495 /// Returns `None` if the pointer is null, or else returns a reference to
496 /// the value wrapped in `Some`.
500 /// While this method and its mutable counterpart are useful for
501 /// null-safety, it is important to note that this is still an unsafe
502 /// operation because the returned value could be pointing to invalid
505 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
506 /// not necessarily reflect the actual lifetime of the data.
513 /// let val: *mut u8 = &mut 10u8 as *mut u8;
516 /// if let Some(val_back) = val.as_ref() {
517 /// println!("We got back the value: {}!", val_back);
521 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
523 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
531 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
532 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
536 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
537 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
538 /// the pointer is used.
545 /// let mut s = [1, 2, 3];
546 /// let ptr: *mut u32 = s.as_mut_ptr();
549 /// println!("{}", *ptr.offset(1));
550 /// println!("{}", *ptr.offset(2));
553 #[stable(feature = "rust1", since = "1.0.0")]
555 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
556 intrinsics::offset(self, count) as *mut T
559 /// Calculates the offset from a pointer using wrapping arithmetic.
560 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
561 /// offset of `3 * sizeof::<T>()` bytes.
565 /// The resulting pointer does not need to be in bounds, but it is
566 /// potentially hazardous to dereference (which requires `unsafe`).
568 /// Always use `.offset(count)` instead when possible, because `offset`
569 /// allows the compiler to optimize better.
576 /// // Iterate using a raw pointer in increments of two elements
577 /// let mut data = [1u8, 2, 3, 4, 5];
578 /// let mut ptr: *mut u8 = data.as_mut_ptr();
580 /// let end_rounded_up = ptr.wrapping_offset(6);
582 /// while ptr != end_rounded_up {
586 /// ptr = ptr.wrapping_offset(step);
588 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
590 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
592 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
594 intrinsics::arith_offset(self, count) as *mut T
598 /// Returns `None` if the pointer is null, or else returns a mutable
599 /// reference to the value wrapped in `Some`.
603 /// As with `as_ref`, this is unsafe because it cannot verify the validity
604 /// of the returned pointer, nor can it ensure that the lifetime `'a`
605 /// returned is indeed a valid lifetime for the contained data.
612 /// let mut s = [1, 2, 3];
613 /// let ptr: *mut u32 = s.as_mut_ptr();
614 /// let first_value = unsafe { ptr.as_mut().unwrap() };
615 /// *first_value = 4;
616 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
618 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
620 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
629 // Equality for pointers
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl<T: ?Sized> PartialEq for *const T {
633 fn eq(&self, other: &*const T) -> bool { *self == *other }
636 #[stable(feature = "rust1", since = "1.0.0")]
637 impl<T: ?Sized> Eq for *const T {}
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl<T: ?Sized> PartialEq for *mut T {
642 fn eq(&self, other: &*mut T) -> bool { *self == *other }
645 #[stable(feature = "rust1", since = "1.0.0")]
646 impl<T: ?Sized> Eq for *mut T {}
648 /// Compare raw pointers for equality.
650 /// This is the same as using the `==` operator, but less generic:
651 /// the arguments have to be `*const T` raw pointers,
652 /// not anything that implements `PartialEq`.
654 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
655 /// by their address rather than comparing the values they point to
656 /// (which is what the `PartialEq for &T` implementation does).
664 /// let other_five = 5;
665 /// let five_ref = &five;
666 /// let same_five_ref = &five;
667 /// let other_five_ref = &other_five;
669 /// assert!(five_ref == same_five_ref);
670 /// assert!(five_ref == other_five_ref);
672 /// assert!(ptr::eq(five_ref, same_five_ref));
673 /// assert!(!ptr::eq(five_ref, other_five_ref));
675 #[stable(feature = "ptr_eq", since = "1.17.0")]
677 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
681 #[stable(feature = "rust1", since = "1.0.0")]
682 impl<T: ?Sized> Clone for *const T {
684 fn clone(&self) -> *const T {
689 #[stable(feature = "rust1", since = "1.0.0")]
690 impl<T: ?Sized> Clone for *mut T {
692 fn clone(&self) -> *mut T {
697 // Impls for function pointers
698 macro_rules! fnptr_impls_safety_abi {
699 ($FnTy: ty, $($Arg: ident),*) => {
700 #[stable(feature = "rust1", since = "1.0.0")]
701 impl<Ret, $($Arg),*> Clone for $FnTy {
703 fn clone(&self) -> Self {
708 #[stable(feature = "fnptr_impls", since = "1.4.0")]
709 impl<Ret, $($Arg),*> PartialEq for $FnTy {
711 fn eq(&self, other: &Self) -> bool {
712 *self as usize == *other as usize
716 #[stable(feature = "fnptr_impls", since = "1.4.0")]
717 impl<Ret, $($Arg),*> Eq for $FnTy {}
719 #[stable(feature = "fnptr_impls", since = "1.4.0")]
720 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
722 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
723 (*self as usize).partial_cmp(&(*other as usize))
727 #[stable(feature = "fnptr_impls", since = "1.4.0")]
728 impl<Ret, $($Arg),*> Ord for $FnTy {
730 fn cmp(&self, other: &Self) -> Ordering {
731 (*self as usize).cmp(&(*other as usize))
735 #[stable(feature = "fnptr_impls", since = "1.4.0")]
736 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
737 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
738 state.write_usize(*self as usize)
742 #[stable(feature = "fnptr_impls", since = "1.4.0")]
743 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
744 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
745 fmt::Pointer::fmt(&(*self as *const ()), f)
749 #[stable(feature = "fnptr_impls", since = "1.4.0")]
750 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
751 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
752 fmt::Pointer::fmt(&(*self as *const ()), f)
758 macro_rules! fnptr_impls_args {
759 ($($Arg: ident),+) => {
760 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
761 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
762 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
763 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
764 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
765 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
768 // No variadic functions with 0 parameters
769 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
770 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
771 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
772 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
776 fnptr_impls_args! { }
777 fnptr_impls_args! { A }
778 fnptr_impls_args! { A, B }
779 fnptr_impls_args! { A, B, C }
780 fnptr_impls_args! { A, B, C, D }
781 fnptr_impls_args! { A, B, C, D, E }
782 fnptr_impls_args! { A, B, C, D, E, F }
783 fnptr_impls_args! { A, B, C, D, E, F, G }
784 fnptr_impls_args! { A, B, C, D, E, F, G, H }
785 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
786 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
787 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
788 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
790 // Comparison for pointers
791 #[stable(feature = "rust1", since = "1.0.0")]
792 impl<T: ?Sized> Ord for *const T {
794 fn cmp(&self, other: &*const T) -> Ordering {
797 } else if self == other {
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl<T: ?Sized> PartialOrd for *const T {
808 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
809 Some(self.cmp(other))
813 fn lt(&self, other: &*const T) -> bool { *self < *other }
816 fn le(&self, other: &*const T) -> bool { *self <= *other }
819 fn gt(&self, other: &*const T) -> bool { *self > *other }
822 fn ge(&self, other: &*const T) -> bool { *self >= *other }
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<T: ?Sized> Ord for *mut T {
828 fn cmp(&self, other: &*mut T) -> Ordering {
831 } else if self == other {
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<T: ?Sized> PartialOrd for *mut T {
842 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
843 Some(self.cmp(other))
847 fn lt(&self, other: &*mut T) -> bool { *self < *other }
850 fn le(&self, other: &*mut T) -> bool { *self <= *other }
853 fn gt(&self, other: &*mut T) -> bool { *self > *other }
856 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
859 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
860 /// of this wrapper owns the referent. This in turn implies that the
861 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
862 /// `*mut T` (which conveys no particular ownership semantics). It
863 /// also implies that the referent of the pointer should not be
864 /// modified without a unique path to the `Unique` reference. Useful
865 /// for building abstractions like `Vec<T>` or `Box<T>`, which
866 /// internally use raw pointers to manage the memory that they own.
867 #[allow(missing_debug_implementations)]
868 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
870 pub struct Unique<T: ?Sized> {
871 pointer: NonZero<*const T>,
872 // NOTE: this marker has no consequences for variance, but is necessary
873 // for dropck to understand that we logically own a `T`.
876 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
877 _marker: PhantomData<T>,
880 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
881 /// reference is unaliased. Note that this aliasing invariant is
882 /// unenforced by the type system; the abstraction using the
883 /// `Unique` must enforce it.
884 #[unstable(feature = "unique", issue = "27730")]
885 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
887 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
888 /// reference is unaliased. Note that this aliasing invariant is
889 /// unenforced by the type system; the abstraction using the
890 /// `Unique` must enforce it.
891 #[unstable(feature = "unique", issue = "27730")]
892 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
894 #[unstable(feature = "unique", issue = "27730")]
895 impl<T: ?Sized> Unique<T> {
896 /// Creates a new `Unique`.
900 /// `ptr` must be non-null.
901 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
902 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
905 /// Dereferences the content.
906 pub unsafe fn get(&self) -> &T {
910 /// Mutably dereferences the content.
911 pub unsafe fn get_mut(&mut self) -> &mut T {
916 #[unstable(feature = "unique", issue = "27730")]
917 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
919 #[unstable(feature = "unique", issue= "27730")]
920 impl<T:?Sized> Deref for Unique<T> {
921 type Target = *mut T;
924 fn deref(&self) -> &*mut T {
925 unsafe { mem::transmute(&*self.pointer) }
929 #[unstable(feature = "unique", issue = "27730")]
930 impl<T> fmt::Pointer for Unique<T> {
931 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
932 fmt::Pointer::fmt(&*self.pointer, f)
936 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
937 /// of this wrapper has shared ownership of the referent. Useful for
938 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
939 /// use raw pointers to manage the memory that they own.
940 #[allow(missing_debug_implementations)]
941 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
943 pub struct Shared<T: ?Sized> {
944 pointer: NonZero<*const T>,
945 // NOTE: this marker has no consequences for variance, but is necessary
946 // for dropck to understand that we logically own a `T`.
949 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
950 _marker: PhantomData<T>,
953 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
954 // NB: This impl is unnecessary, but should provide better error messages.
955 #[unstable(feature = "shared", issue = "27730")]
956 impl<T: ?Sized> !Send for Shared<T> { }
958 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
959 // NB: This impl is unnecessary, but should provide better error messages.
960 #[unstable(feature = "shared", issue = "27730")]
961 impl<T: ?Sized> !Sync for Shared<T> { }
963 #[unstable(feature = "shared", issue = "27730")]
964 impl<T: ?Sized> Shared<T> {
965 /// Creates a new `Shared`.
969 /// `ptr` must be non-null.
970 pub unsafe fn new(ptr: *const T) -> Self {
971 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
975 #[unstable(feature = "shared", issue = "27730")]
976 impl<T: ?Sized> Shared<T> {
977 /// Acquires the underlying pointer as a `*mut` pointer.
978 pub unsafe fn as_mut_ptr(&self) -> *mut T {
983 #[unstable(feature = "shared", issue = "27730")]
984 impl<T: ?Sized> Clone for Shared<T> {
985 fn clone(&self) -> Self {
990 #[unstable(feature = "shared", issue = "27730")]
991 impl<T: ?Sized> Copy for Shared<T> { }
993 #[unstable(feature = "shared", issue = "27730")]
994 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
996 #[unstable(feature = "shared", issue = "27730")]
997 impl<T: ?Sized> Deref for Shared<T> {
998 type Target = *const T;
1001 fn deref(&self) -> &*const T {
1002 unsafe { mem::transmute(&*self.pointer) }
1006 #[unstable(feature = "shared", issue = "27730")]
1007 impl<T> fmt::Pointer for Shared<T> {
1008 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1009 fmt::Pointer::fmt(&*self.pointer, f)