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`.
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 /// It does not immediately drop the contents of `src` either; it is rather
195 /// *moved* into the memory location `dst` and will be dropped whenever that
196 /// location goes out of scope.
198 /// This is appropriate for initializing uninitialized memory, or overwriting
199 /// memory that has previously been `read` from.
201 /// The pointer must be aligned; use `write_unaligned` if that is not the case.
209 /// let y = &mut x as *mut i32;
213 /// std::ptr::write(y, z);
214 /// assert_eq!(std::ptr::read(y), 12);
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub unsafe fn write<T>(dst: *mut T, src: T) {
220 intrinsics::move_val_init(&mut *dst, src)
223 /// Overwrites a memory location with the given value without reading or
224 /// dropping the old value.
226 /// Unlike `write`, the pointer may be unaligned.
230 /// This operation is marked unsafe because it accepts a raw pointer.
232 /// It does not drop the contents of `dst`. This is safe, but it could leak
233 /// allocations or resources, so care must be taken not to overwrite an object
234 /// that should be dropped.
236 /// This is appropriate for initializing uninitialized memory, or overwriting
237 /// memory that has previously been `read` from.
244 /// #![feature(ptr_unaligned)]
247 /// let y = &mut x as *mut i32;
251 /// std::ptr::write_unaligned(y, z);
252 /// assert_eq!(std::ptr::read_unaligned(y), 12);
256 #[unstable(feature = "ptr_unaligned", issue = "37955")]
257 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
258 copy_nonoverlapping(&src as *const T as *const u8,
260 mem::size_of::<T>());
264 /// Performs a volatile read of the value from `src` without moving it. This
265 /// leaves the memory in `src` unchanged.
267 /// Volatile operations are intended to act on I/O memory, and are guaranteed
268 /// to not be elided or reordered by the compiler across other volatile
273 /// Rust does not currently have a rigorously and formally defined memory model,
274 /// so the precise semantics of what "volatile" means here is subject to change
275 /// over time. That being said, the semantics will almost always end up pretty
276 /// similar to [C11's definition of volatile][c11].
278 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
282 /// Beyond accepting a raw pointer, this is unsafe because it semantically
283 /// moves the value out of `src` without preventing further usage of `src`.
284 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
285 /// `src` is not used before the data is overwritten again (e.g. with `write`,
286 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
287 /// because it will attempt to drop the value previously at `*src`.
295 /// let y = &x as *const i32;
298 /// assert_eq!(std::ptr::read_volatile(y), 12);
302 #[stable(feature = "volatile", since = "1.9.0")]
303 pub unsafe fn read_volatile<T>(src: *const T) -> T {
304 intrinsics::volatile_load(src)
307 /// Performs a volatile write of a memory location with the given value without
308 /// reading or dropping the old value.
310 /// Volatile operations are intended to act on I/O memory, and are guaranteed
311 /// to not be elided or reordered by the compiler across other volatile
316 /// Rust does not currently have a rigorously and formally defined memory model,
317 /// so the precise semantics of what "volatile" means here is subject to change
318 /// over time. That being said, the semantics will almost always end up pretty
319 /// similar to [C11's definition of volatile][c11].
321 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
325 /// This operation is marked unsafe because it accepts a raw pointer.
327 /// It does not drop the contents of `dst`. This is safe, but it could leak
328 /// allocations or resources, so care must be taken not to overwrite an object
329 /// that should be dropped.
331 /// This is appropriate for initializing uninitialized memory, or overwriting
332 /// memory that has previously been `read` from.
340 /// let y = &mut x as *mut i32;
344 /// std::ptr::write_volatile(y, z);
345 /// assert_eq!(std::ptr::read_volatile(y), 12);
349 #[stable(feature = "volatile", since = "1.9.0")]
350 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
351 intrinsics::volatile_store(dst, src);
354 #[lang = "const_ptr"]
355 impl<T: ?Sized> *const T {
356 /// Returns true if the pointer is null.
363 /// let s: &str = "Follow the rabbit";
364 /// let ptr: *const u8 = s.as_ptr();
365 /// assert!(!ptr.is_null());
367 #[stable(feature = "rust1", since = "1.0.0")]
369 pub fn is_null(self) -> bool where T: Sized {
373 /// Returns `None` if the pointer is null, or else returns a reference to
374 /// the value wrapped in `Some`.
378 /// While this method and its mutable counterpart are useful for
379 /// null-safety, it is important to note that this is still an unsafe
380 /// operation because the returned value could be pointing to invalid
383 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
384 /// not necessarily reflect the actual lifetime of the data.
391 /// let val: *const u8 = &10u8 as *const u8;
394 /// if let Some(val_back) = val.as_ref() {
395 /// println!("We got back the value: {}!", val_back);
399 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
401 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
409 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
410 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
414 /// Both the starting and resulting pointer must be either in bounds or one
415 /// byte past the end of an allocated object. If either pointer is out of
416 /// bounds or arithmetic overflow occurs then
417 /// any further use of the returned value will result in undefined behavior.
424 /// let s: &str = "123";
425 /// let ptr: *const u8 = s.as_ptr();
428 /// println!("{}", *ptr.offset(1) as char);
429 /// println!("{}", *ptr.offset(2) as char);
432 #[stable(feature = "rust1", since = "1.0.0")]
434 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
435 intrinsics::offset(self, count)
438 /// Calculates the offset from a pointer using wrapping arithmetic.
439 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
440 /// offset of `3 * sizeof::<T>()` bytes.
444 /// The resulting pointer does not need to be in bounds, but it is
445 /// potentially hazardous to dereference (which requires `unsafe`).
447 /// Always use `.offset(count)` instead when possible, because `offset`
448 /// allows the compiler to optimize better.
455 /// // Iterate using a raw pointer in increments of two elements
456 /// let data = [1u8, 2, 3, 4, 5];
457 /// let mut ptr: *const u8 = data.as_ptr();
459 /// let end_rounded_up = ptr.wrapping_offset(6);
461 /// // This loop prints "1, 3, 5, "
462 /// while ptr != end_rounded_up {
464 /// print!("{}, ", *ptr);
466 /// ptr = ptr.wrapping_offset(step);
469 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
471 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
473 intrinsics::arith_offset(self, count)
479 impl<T: ?Sized> *mut T {
480 /// Returns true if the pointer is null.
487 /// let mut s = [1, 2, 3];
488 /// let ptr: *mut u32 = s.as_mut_ptr();
489 /// assert!(!ptr.is_null());
491 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn is_null(self) -> bool where T: Sized {
497 /// Returns `None` if the pointer is null, or else returns a reference to
498 /// the value wrapped in `Some`.
502 /// While this method and its mutable counterpart are useful for
503 /// null-safety, it is important to note that this is still an unsafe
504 /// operation because the returned value could be pointing to invalid
507 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
508 /// not necessarily reflect the actual lifetime of the data.
515 /// let val: *mut u8 = &mut 10u8 as *mut u8;
518 /// if let Some(val_back) = val.as_ref() {
519 /// println!("We got back the value: {}!", val_back);
523 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
525 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
533 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
534 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
538 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
539 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
540 /// the pointer is used.
547 /// let mut s = [1, 2, 3];
548 /// let ptr: *mut u32 = s.as_mut_ptr();
551 /// println!("{}", *ptr.offset(1));
552 /// println!("{}", *ptr.offset(2));
555 #[stable(feature = "rust1", since = "1.0.0")]
557 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
558 intrinsics::offset(self, count) as *mut T
561 /// Calculates the offset from a pointer using wrapping arithmetic.
562 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
563 /// offset of `3 * sizeof::<T>()` bytes.
567 /// The resulting pointer does not need to be in bounds, but it is
568 /// potentially hazardous to dereference (which requires `unsafe`).
570 /// Always use `.offset(count)` instead when possible, because `offset`
571 /// allows the compiler to optimize better.
578 /// // Iterate using a raw pointer in increments of two elements
579 /// let mut data = [1u8, 2, 3, 4, 5];
580 /// let mut ptr: *mut u8 = data.as_mut_ptr();
582 /// let end_rounded_up = ptr.wrapping_offset(6);
584 /// while ptr != end_rounded_up {
588 /// ptr = ptr.wrapping_offset(step);
590 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
592 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
594 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
596 intrinsics::arith_offset(self, count) as *mut T
600 /// Returns `None` if the pointer is null, or else returns a mutable
601 /// reference to the value wrapped in `Some`.
605 /// As with `as_ref`, this is unsafe because it cannot verify the validity
606 /// of the returned pointer, nor can it ensure that the lifetime `'a`
607 /// returned is indeed a valid lifetime for the contained data.
614 /// let mut s = [1, 2, 3];
615 /// let ptr: *mut u32 = s.as_mut_ptr();
616 /// let first_value = unsafe { ptr.as_mut().unwrap() };
617 /// *first_value = 4;
618 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
620 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
622 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
631 // Equality for pointers
632 #[stable(feature = "rust1", since = "1.0.0")]
633 impl<T: ?Sized> PartialEq for *const T {
635 fn eq(&self, other: &*const T) -> bool { *self == *other }
638 #[stable(feature = "rust1", since = "1.0.0")]
639 impl<T: ?Sized> Eq for *const T {}
641 #[stable(feature = "rust1", since = "1.0.0")]
642 impl<T: ?Sized> PartialEq for *mut T {
644 fn eq(&self, other: &*mut T) -> bool { *self == *other }
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl<T: ?Sized> Eq for *mut T {}
650 /// Compare raw pointers for equality.
652 /// This is the same as using the `==` operator, but less generic:
653 /// the arguments have to be `*const T` raw pointers,
654 /// not anything that implements `PartialEq`.
656 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
657 /// by their address rather than comparing the values they point to
658 /// (which is what the `PartialEq for &T` implementation does).
663 /// #![feature(ptr_eq)]
667 /// let other_five = 5;
668 /// let five_ref = &five;
669 /// let same_five_ref = &five;
670 /// let other_five_ref = &other_five;
672 /// assert!(five_ref == same_five_ref);
673 /// assert!(five_ref == other_five_ref);
675 /// assert!(ptr::eq(five_ref, same_five_ref));
676 /// assert!(!ptr::eq(five_ref, other_five_ref));
678 #[unstable(feature = "ptr_eq", reason = "newly added", issue = "36497")]
680 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl<T: ?Sized> Clone for *const T {
687 fn clone(&self) -> *const T {
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl<T: ?Sized> Clone for *mut T {
695 fn clone(&self) -> *mut T {
700 // Impls for function pointers
701 macro_rules! fnptr_impls_safety_abi {
702 ($FnTy: ty, $($Arg: ident),*) => {
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<Ret, $($Arg),*> Clone for $FnTy {
706 fn clone(&self) -> Self {
711 #[stable(feature = "fnptr_impls", since = "1.4.0")]
712 impl<Ret, $($Arg),*> PartialEq for $FnTy {
714 fn eq(&self, other: &Self) -> bool {
715 *self as usize == *other as usize
719 #[stable(feature = "fnptr_impls", since = "1.4.0")]
720 impl<Ret, $($Arg),*> Eq for $FnTy {}
722 #[stable(feature = "fnptr_impls", since = "1.4.0")]
723 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
725 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
726 (*self as usize).partial_cmp(&(*other as usize))
730 #[stable(feature = "fnptr_impls", since = "1.4.0")]
731 impl<Ret, $($Arg),*> Ord for $FnTy {
733 fn cmp(&self, other: &Self) -> Ordering {
734 (*self as usize).cmp(&(*other as usize))
738 #[stable(feature = "fnptr_impls", since = "1.4.0")]
739 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
740 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
741 state.write_usize(*self as usize)
745 #[stable(feature = "fnptr_impls", since = "1.4.0")]
746 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
747 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
748 fmt::Pointer::fmt(&(*self as *const ()), f)
752 #[stable(feature = "fnptr_impls", since = "1.4.0")]
753 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
754 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
755 fmt::Pointer::fmt(&(*self as *const ()), f)
761 macro_rules! fnptr_impls_args {
762 ($($Arg: ident),+) => {
763 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
764 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
765 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
766 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
767 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
768 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
771 // No variadic functions with 0 parameters
772 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
773 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
774 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
775 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
779 fnptr_impls_args! { }
780 fnptr_impls_args! { A }
781 fnptr_impls_args! { A, B }
782 fnptr_impls_args! { A, B, C }
783 fnptr_impls_args! { A, B, C, D }
784 fnptr_impls_args! { A, B, C, D, E }
785 fnptr_impls_args! { A, B, C, D, E, F }
786 fnptr_impls_args! { A, B, C, D, E, F, G }
787 fnptr_impls_args! { A, B, C, D, E, F, G, H }
788 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
789 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
790 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
791 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
793 // Comparison for pointers
794 #[stable(feature = "rust1", since = "1.0.0")]
795 impl<T: ?Sized> Ord for *const T {
797 fn cmp(&self, other: &*const T) -> Ordering {
800 } else if self == other {
808 #[stable(feature = "rust1", since = "1.0.0")]
809 impl<T: ?Sized> PartialOrd for *const T {
811 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
812 Some(self.cmp(other))
816 fn lt(&self, other: &*const T) -> bool { *self < *other }
819 fn le(&self, other: &*const T) -> bool { *self <= *other }
822 fn gt(&self, other: &*const T) -> bool { *self > *other }
825 fn ge(&self, other: &*const T) -> bool { *self >= *other }
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl<T: ?Sized> Ord for *mut T {
831 fn cmp(&self, other: &*mut T) -> Ordering {
834 } else if self == other {
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<T: ?Sized> PartialOrd for *mut T {
845 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
846 Some(self.cmp(other))
850 fn lt(&self, other: &*mut T) -> bool { *self < *other }
853 fn le(&self, other: &*mut T) -> bool { *self <= *other }
856 fn gt(&self, other: &*mut T) -> bool { *self > *other }
859 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
862 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
863 /// of this wrapper owns the referent. This in turn implies that the
864 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
865 /// `*mut T` (which conveys no particular ownership semantics). It
866 /// also implies that the referent of the pointer should not be
867 /// modified without a unique path to the `Unique` reference. Useful
868 /// for building abstractions like `Vec<T>` or `Box<T>`, which
869 /// internally use raw pointers to manage the memory that they own.
870 #[allow(missing_debug_implementations)]
871 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
873 pub struct Unique<T: ?Sized> {
874 pointer: NonZero<*const T>,
875 // NOTE: this marker has no consequences for variance, but is necessary
876 // for dropck to understand that we logically own a `T`.
879 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
880 _marker: PhantomData<T>,
883 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
884 /// reference is unaliased. Note that this aliasing invariant is
885 /// unenforced by the type system; the abstraction using the
886 /// `Unique` must enforce it.
887 #[unstable(feature = "unique", issue = "27730")]
888 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
890 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
891 /// reference is unaliased. Note that this aliasing invariant is
892 /// unenforced by the type system; the abstraction using the
893 /// `Unique` must enforce it.
894 #[unstable(feature = "unique", issue = "27730")]
895 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
897 #[unstable(feature = "unique", issue = "27730")]
898 impl<T: ?Sized> Unique<T> {
899 /// Creates a new `Unique`.
903 /// `ptr` must be non-null.
904 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
905 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
908 /// Dereferences the content.
909 pub unsafe fn get(&self) -> &T {
913 /// Mutably dereferences the content.
914 pub unsafe fn get_mut(&mut self) -> &mut T {
919 #[unstable(feature = "unique", issue = "27730")]
920 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
922 #[unstable(feature = "unique", issue= "27730")]
923 impl<T:?Sized> Deref for Unique<T> {
924 type Target = *mut T;
927 fn deref(&self) -> &*mut T {
928 unsafe { mem::transmute(&*self.pointer) }
932 #[unstable(feature = "unique", issue = "27730")]
933 impl<T> fmt::Pointer for Unique<T> {
934 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
935 fmt::Pointer::fmt(&*self.pointer, f)
939 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
940 /// of this wrapper has shared ownership of the referent. Useful for
941 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
942 /// use raw pointers to manage the memory that they own.
943 #[allow(missing_debug_implementations)]
944 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
946 pub struct Shared<T: ?Sized> {
947 pointer: NonZero<*const T>,
948 // NOTE: this marker has no consequences for variance, but is necessary
949 // for dropck to understand that we logically own a `T`.
952 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
953 _marker: PhantomData<T>,
956 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
957 // NB: This impl is unnecessary, but should provide better error messages.
958 #[unstable(feature = "shared", issue = "27730")]
959 impl<T: ?Sized> !Send for Shared<T> { }
961 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
962 // NB: This impl is unnecessary, but should provide better error messages.
963 #[unstable(feature = "shared", issue = "27730")]
964 impl<T: ?Sized> !Sync for Shared<T> { }
966 #[unstable(feature = "shared", issue = "27730")]
967 impl<T: ?Sized> Shared<T> {
968 /// Creates a new `Shared`.
972 /// `ptr` must be non-null.
973 pub unsafe fn new(ptr: *mut T) -> Self {
974 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
978 #[unstable(feature = "shared", issue = "27730")]
979 impl<T: ?Sized> Clone for Shared<T> {
980 fn clone(&self) -> Self {
985 #[unstable(feature = "shared", issue = "27730")]
986 impl<T: ?Sized> Copy for Shared<T> { }
988 #[unstable(feature = "shared", issue = "27730")]
989 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
991 #[unstable(feature = "shared", issue = "27730")]
992 impl<T: ?Sized> Deref for Shared<T> {
993 type Target = *mut T;
996 fn deref(&self) -> &*mut T {
997 unsafe { mem::transmute(&*self.pointer) }
1001 #[unstable(feature = "shared", issue = "27730")]
1002 impl<T> fmt::Pointer for Shared<T> {
1003 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1004 fmt::Pointer::fmt(&*self.pointer, f)