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
78 /// as arguments, which means they will be dereferenced.
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`.
164 /// #![feature(ptr_unaligned)]
167 /// let y = &x as *const i32;
170 /// assert_eq!(std::ptr::read_unaligned(y), 12);
174 #[unstable(feature = "ptr_unaligned", issue = "37955")]
175 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
176 let mut tmp: T = mem::uninitialized();
177 copy_nonoverlapping(src as *const u8,
178 &mut tmp as *mut T as *mut u8,
179 mem::size_of::<T>());
183 /// Overwrites a memory location with the given value without reading or
184 /// dropping the old value.
188 /// This operation is marked unsafe because it accepts a raw pointer.
190 /// It does not drop the contents of `dst`. This is safe, but it could leak
191 /// allocations or resources, so care must be taken not to overwrite an object
192 /// that should be dropped.
194 /// This is appropriate for initializing uninitialized memory, or overwriting
195 /// memory that has previously been `read` from.
197 /// The pointer must be aligned; use `write_unaligned` if that is not the case.
205 /// let y = &mut x as *mut i32;
209 /// std::ptr::write(y, z);
210 /// assert_eq!(std::ptr::read(y), 12);
214 #[stable(feature = "rust1", since = "1.0.0")]
215 pub unsafe fn write<T>(dst: *mut T, src: T) {
216 intrinsics::move_val_init(&mut *dst, src)
219 /// Overwrites a memory location with the given value without reading or
220 /// dropping the old value.
222 /// Unlike `write`, the pointer may be unaligned.
226 /// This operation is marked unsafe because it accepts a raw pointer.
228 /// It does not drop the contents of `dst`. This is safe, but it could leak
229 /// allocations or resources, so care must be taken not to overwrite an object
230 /// that should be dropped.
232 /// This is appropriate for initializing uninitialized memory, or overwriting
233 /// memory that has previously been `read` from.
240 /// #![feature(ptr_unaligned)]
243 /// let y = &mut x as *mut i32;
247 /// std::ptr::write_unaligned(y, z);
248 /// assert_eq!(std::ptr::read_unaligned(y), 12);
252 #[unstable(feature = "ptr_unaligned", issue = "37955")]
253 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
254 copy_nonoverlapping(&src as *const T as *const u8,
256 mem::size_of::<T>());
260 /// Performs a volatile read of the value from `src` without moving it. This
261 /// leaves the memory in `src` unchanged.
263 /// Volatile operations are intended to act on I/O memory, and are guaranteed
264 /// to not be elided or reordered by the compiler across other volatile
269 /// Rust does not currently have a rigorously and formally defined memory model,
270 /// so the precise semantics of what "volatile" means here is subject to change
271 /// over time. That being said, the semantics will almost always end up pretty
272 /// similar to [C11's definition of volatile][c11].
274 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
278 /// Beyond accepting a raw pointer, this is unsafe because it semantically
279 /// moves the value out of `src` without preventing further usage of `src`.
280 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
281 /// `src` is not used before the data is overwritten again (e.g. with `write`,
282 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
283 /// because it will attempt to drop the value previously at `*src`.
291 /// let y = &x as *const i32;
294 /// assert_eq!(std::ptr::read_volatile(y), 12);
298 #[stable(feature = "volatile", since = "1.9.0")]
299 pub unsafe fn read_volatile<T>(src: *const T) -> T {
300 intrinsics::volatile_load(src)
303 /// Performs a volatile write of a memory location with the given value without
304 /// reading or dropping the old value.
306 /// Volatile operations are intended to act on I/O memory, and are guaranteed
307 /// to not be elided or reordered by the compiler across other volatile
312 /// Rust does not currently have a rigorously and formally defined memory model,
313 /// so the precise semantics of what "volatile" means here is subject to change
314 /// over time. That being said, the semantics will almost always end up pretty
315 /// similar to [C11's definition of volatile][c11].
317 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
321 /// This operation is marked unsafe because it accepts a raw pointer.
323 /// It does not drop the contents of `dst`. This is safe, but it could leak
324 /// allocations or resources, so care must be taken not to overwrite an object
325 /// that should be dropped.
327 /// This is appropriate for initializing uninitialized memory, or overwriting
328 /// memory that has previously been `read` from.
336 /// let y = &mut x as *mut i32;
340 /// std::ptr::write_volatile(y, z);
341 /// assert_eq!(std::ptr::read_volatile(y), 12);
345 #[stable(feature = "volatile", since = "1.9.0")]
346 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
347 intrinsics::volatile_store(dst, src);
350 #[lang = "const_ptr"]
351 impl<T: ?Sized> *const T {
352 /// Returns true if the pointer is null.
359 /// let s: &str = "Follow the rabbit";
360 /// let ptr: *const u8 = s.as_ptr();
361 /// assert!(!ptr.is_null());
363 #[stable(feature = "rust1", since = "1.0.0")]
365 pub fn is_null(self) -> bool where T: Sized {
369 /// Returns `None` if the pointer is null, or else returns a reference to
370 /// the value wrapped in `Some`.
374 /// While this method and its mutable counterpart are useful for
375 /// null-safety, it is important to note that this is still an unsafe
376 /// operation because the returned value could be pointing to invalid
379 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
380 /// not necessarily reflect the actual lifetime of the data.
387 /// let val: *const u8 = &10u8 as *const u8;
390 /// if let Some(val_back) = val.as_ref() {
391 /// println!("We got back the value: {}!", val_back);
395 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
397 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
405 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
406 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
410 /// Both the starting and resulting pointer must be either in bounds or one
411 /// byte past the end of an allocated object. If either pointer is out of
412 /// bounds or arithmetic overflow occurs then
413 /// any further use of the returned value will result in undefined behavior.
420 /// let s: &str = "123";
421 /// let ptr: *const u8 = s.as_ptr();
424 /// println!("{}", *ptr.offset(1) as char);
425 /// println!("{}", *ptr.offset(2) as char);
428 #[stable(feature = "rust1", since = "1.0.0")]
430 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
431 intrinsics::offset(self, count)
434 /// Calculates the offset from a pointer using wrapping arithmetic.
435 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
436 /// offset of `3 * sizeof::<T>()` bytes.
440 /// The resulting pointer does not need to be in bounds, but it is
441 /// potentially hazardous to dereference (which requires `unsafe`).
443 /// Always use `.offset(count)` instead when possible, because `offset`
444 /// allows the compiler to optimize better.
451 /// #![feature(ptr_wrapping_offset)]
452 /// // Iterate using a raw pointer in increments of two elements
453 /// let data = [1u8, 2, 3, 4, 5];
454 /// let mut ptr: *const u8 = data.as_ptr();
456 /// let end_rounded_up = ptr.wrapping_offset(6);
458 /// // This loop prints "1, 3, 5, "
459 /// while ptr != end_rounded_up {
461 /// print!("{}, ", *ptr);
463 /// ptr = ptr.wrapping_offset(step);
466 #[unstable(feature = "ptr_wrapping_offset", issue = "37570")]
468 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
470 intrinsics::arith_offset(self, count)
476 impl<T: ?Sized> *mut T {
477 /// Returns true if the pointer is null.
484 /// let mut s = [1, 2, 3];
485 /// let ptr: *mut u32 = s.as_mut_ptr();
486 /// assert!(!ptr.is_null());
488 #[stable(feature = "rust1", since = "1.0.0")]
490 pub fn is_null(self) -> bool where T: Sized {
494 /// Returns `None` if the pointer is null, or else returns a reference to
495 /// the value wrapped in `Some`.
499 /// While this method and its mutable counterpart are useful for
500 /// null-safety, it is important to note that this is still an unsafe
501 /// operation because the returned value could be pointing to invalid
504 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
505 /// not necessarily reflect the actual lifetime of the data.
512 /// let val: *mut u8 = &mut 10u8 as *mut u8;
515 /// if let Some(val_back) = val.as_ref() {
516 /// println!("We got back the value: {}!", val_back);
520 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
522 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
530 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
531 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
535 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
536 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
537 /// the pointer is used.
544 /// let mut s = [1, 2, 3];
545 /// let ptr: *mut u32 = s.as_mut_ptr();
548 /// println!("{}", *ptr.offset(1));
549 /// println!("{}", *ptr.offset(2));
552 #[stable(feature = "rust1", since = "1.0.0")]
554 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
555 intrinsics::offset(self, count) as *mut T
558 /// Calculates the offset from a pointer using wrapping arithmetic.
559 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
560 /// offset of `3 * sizeof::<T>()` bytes.
564 /// The resulting pointer does not need to be in bounds, but it is
565 /// potentially hazardous to dereference (which requires `unsafe`).
567 /// Always use `.offset(count)` instead when possible, because `offset`
568 /// allows the compiler to optimize better.
575 /// #![feature(ptr_wrapping_offset)]
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 #[unstable(feature = "ptr_wrapping_offset", issue = "37570")]
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).
661 /// #![feature(ptr_eq)]
665 /// let other_five = 5;
666 /// let five_ref = &five;
667 /// let same_five_ref = &five;
668 /// let other_five_ref = &other_five;
670 /// assert!(five_ref == same_five_ref);
671 /// assert!(five_ref == other_five_ref);
673 /// assert!(ptr::eq(five_ref, same_five_ref));
674 /// assert!(!ptr::eq(five_ref, other_five_ref));
676 #[unstable(feature = "ptr_eq", reason = "newly added", issue = "36497")]
678 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
682 #[stable(feature = "rust1", since = "1.0.0")]
683 impl<T: ?Sized> Clone for *const T {
685 fn clone(&self) -> *const T {
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl<T: ?Sized> Clone for *mut T {
693 fn clone(&self) -> *mut T {
698 // Impls for function pointers
699 macro_rules! fnptr_impls_safety_abi {
700 ($FnTy: ty, $($Arg: ident),*) => {
701 #[stable(feature = "rust1", since = "1.0.0")]
702 impl<Ret, $($Arg),*> Clone for $FnTy {
704 fn clone(&self) -> Self {
709 #[stable(feature = "fnptr_impls", since = "1.4.0")]
710 impl<Ret, $($Arg),*> PartialEq for $FnTy {
712 fn eq(&self, other: &Self) -> bool {
713 *self as usize == *other as usize
717 #[stable(feature = "fnptr_impls", since = "1.4.0")]
718 impl<Ret, $($Arg),*> Eq for $FnTy {}
720 #[stable(feature = "fnptr_impls", since = "1.4.0")]
721 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
723 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
724 (*self as usize).partial_cmp(&(*other as usize))
728 #[stable(feature = "fnptr_impls", since = "1.4.0")]
729 impl<Ret, $($Arg),*> Ord for $FnTy {
731 fn cmp(&self, other: &Self) -> Ordering {
732 (*self as usize).cmp(&(*other as usize))
736 #[stable(feature = "fnptr_impls", since = "1.4.0")]
737 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
738 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
739 state.write_usize(*self as usize)
743 #[stable(feature = "fnptr_impls", since = "1.4.0")]
744 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
745 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
746 fmt::Pointer::fmt(&(*self as *const ()), f)
750 #[stable(feature = "fnptr_impls", since = "1.4.0")]
751 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
752 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
753 fmt::Pointer::fmt(&(*self as *const ()), f)
759 macro_rules! fnptr_impls_args {
760 ($($Arg: ident),+) => {
761 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
762 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
763 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
764 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
765 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
766 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
769 // No variadic functions with 0 parameters
770 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
771 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
772 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
773 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
777 fnptr_impls_args! { }
778 fnptr_impls_args! { A }
779 fnptr_impls_args! { A, B }
780 fnptr_impls_args! { A, B, C }
781 fnptr_impls_args! { A, B, C, D }
782 fnptr_impls_args! { A, B, C, D, E }
783 fnptr_impls_args! { A, B, C, D, E, F }
784 fnptr_impls_args! { A, B, C, D, E, F, G }
785 fnptr_impls_args! { A, B, C, D, E, F, G, H }
786 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
787 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
788 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
789 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
791 // Comparison for pointers
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl<T: ?Sized> Ord for *const T {
795 fn cmp(&self, other: &*const T) -> Ordering {
798 } else if self == other {
806 #[stable(feature = "rust1", since = "1.0.0")]
807 impl<T: ?Sized> PartialOrd for *const T {
809 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
810 Some(self.cmp(other))
814 fn lt(&self, other: &*const T) -> bool { *self < *other }
817 fn le(&self, other: &*const T) -> bool { *self <= *other }
820 fn gt(&self, other: &*const T) -> bool { *self > *other }
823 fn ge(&self, other: &*const T) -> bool { *self >= *other }
826 #[stable(feature = "rust1", since = "1.0.0")]
827 impl<T: ?Sized> Ord for *mut T {
829 fn cmp(&self, other: &*mut T) -> Ordering {
832 } else if self == other {
840 #[stable(feature = "rust1", since = "1.0.0")]
841 impl<T: ?Sized> PartialOrd for *mut T {
843 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
844 Some(self.cmp(other))
848 fn lt(&self, other: &*mut T) -> bool { *self < *other }
851 fn le(&self, other: &*mut T) -> bool { *self <= *other }
854 fn gt(&self, other: &*mut T) -> bool { *self > *other }
857 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
860 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
861 /// of this wrapper owns the referent. This in turn implies that the
862 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
863 /// `*mut T` (which conveys no particular ownership semantics). It
864 /// also implies that the referent of the pointer should not be
865 /// modified without a unique path to the `Unique` reference. Useful
866 /// for building abstractions like `Vec<T>` or `Box<T>`, which
867 /// internally use raw pointers to manage the memory that they own.
868 #[allow(missing_debug_implementations)]
869 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
871 pub struct Unique<T: ?Sized> {
872 pointer: NonZero<*const T>,
873 // NOTE: this marker has no consequences for variance, but is necessary
874 // for dropck to understand that we logically own a `T`.
877 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
878 _marker: PhantomData<T>,
881 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
882 /// reference is unaliased. Note that this aliasing invariant is
883 /// unenforced by the type system; the abstraction using the
884 /// `Unique` must enforce it.
885 #[unstable(feature = "unique", issue = "27730")]
886 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
888 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
889 /// reference is unaliased. Note that this aliasing invariant is
890 /// unenforced by the type system; the abstraction using the
891 /// `Unique` must enforce it.
892 #[unstable(feature = "unique", issue = "27730")]
893 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
895 #[unstable(feature = "unique", issue = "27730")]
896 impl<T: ?Sized> Unique<T> {
897 /// Creates a new `Unique`.
901 /// `ptr` must be non-null.
902 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
903 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
906 /// Dereferences the content.
907 pub unsafe fn get(&self) -> &T {
911 /// Mutably dereferences the content.
912 pub unsafe fn get_mut(&mut self) -> &mut T {
917 #[unstable(feature = "unique", issue = "27730")]
918 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
920 #[unstable(feature = "unique", issue= "27730")]
921 impl<T:?Sized> Deref for Unique<T> {
922 type Target = *mut T;
925 fn deref(&self) -> &*mut T {
926 unsafe { mem::transmute(&*self.pointer) }
930 #[unstable(feature = "unique", issue = "27730")]
931 impl<T> fmt::Pointer for Unique<T> {
932 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
933 fmt::Pointer::fmt(&*self.pointer, f)
937 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
938 /// of this wrapper has shared ownership of the referent. Useful for
939 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
940 /// use raw pointers to manage the memory that they own.
941 #[allow(missing_debug_implementations)]
942 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
944 pub struct Shared<T: ?Sized> {
945 pointer: NonZero<*const T>,
946 // NOTE: this marker has no consequences for variance, but is necessary
947 // for dropck to understand that we logically own a `T`.
950 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
951 _marker: PhantomData<T>,
954 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
955 // NB: This impl is unnecessary, but should provide better error messages.
956 #[unstable(feature = "shared", issue = "27730")]
957 impl<T: ?Sized> !Send for Shared<T> { }
959 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
960 // NB: This impl is unnecessary, but should provide better error messages.
961 #[unstable(feature = "shared", issue = "27730")]
962 impl<T: ?Sized> !Sync for Shared<T> { }
964 #[unstable(feature = "shared", issue = "27730")]
965 impl<T: ?Sized> Shared<T> {
966 /// Creates a new `Shared`.
970 /// `ptr` must be non-null.
971 pub unsafe fn new(ptr: *mut T) -> Self {
972 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
976 #[unstable(feature = "shared", issue = "27730")]
977 impl<T: ?Sized> Clone for Shared<T> {
978 fn clone(&self) -> Self {
983 #[unstable(feature = "shared", issue = "27730")]
984 impl<T: ?Sized> Copy for Shared<T> { }
986 #[unstable(feature = "shared", issue = "27730")]
987 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
989 #[unstable(feature = "shared", issue = "27730")]
990 impl<T: ?Sized> Deref for Shared<T> {
991 type Target = *mut T;
994 fn deref(&self) -> &*mut T {
995 unsafe { mem::transmute(&*self.pointer) }
999 #[unstable(feature = "shared", issue = "27730")]
1000 impl<T> fmt::Pointer for Shared<T> {
1001 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1002 fmt::Pointer::fmt(&*self.pointer, f)