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")]
21 use ops::{CoerceUnsized, Deref};
24 use option::Option::{self, Some, None};
25 use marker::{Copy, PhantomData, Send, Sized, Sync, Unsize};
29 use cmp::{PartialEq, Eq, Ord, PartialOrd};
30 use cmp::Ordering::{self, Less, Equal, Greater};
32 // FIXME #19649: intrinsic docs don't render, so these have no docs :(
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use intrinsics::copy_nonoverlapping;
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use intrinsics::copy;
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub use intrinsics::write_bytes;
43 #[stable(feature = "drop_in_place", since = "1.8.0")]
44 pub use intrinsics::drop_in_place;
46 /// Creates a null raw pointer.
53 /// let p: *const i32 = ptr::null();
54 /// assert!(p.is_null());
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub const fn null<T>() -> *const T { 0 as *const T }
60 /// Creates a null mutable raw pointer.
67 /// let p: *mut i32 = ptr::null_mut();
68 /// assert!(p.is_null());
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
74 /// Swaps the values at two mutable locations of the same type, without
75 /// deinitializing either. They may overlap, unlike `mem::swap` which is
76 /// otherwise equivalent.
80 /// This is only unsafe because it accepts a raw pointer.
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`.
129 /// let y = &x as *const i32;
131 /// unsafe { println!("{}", std::ptr::read(y)); }
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub unsafe fn read<T>(src: *const T) -> T {
136 let mut tmp: T = mem::uninitialized();
137 copy_nonoverlapping(src, &mut tmp, 1);
141 #[allow(missing_docs)]
143 #[unstable(feature = "filling_drop",
144 reason = "may play a larger role in std::ptr future extensions",
146 pub unsafe fn read_and_drop<T>(dest: *mut T) -> T {
147 // Copy the data out from `dest`:
148 let tmp = read(&*dest);
150 // Now mark `dest` as dropped:
151 write_bytes(dest, mem::POST_DROP_U8, 1);
156 /// Overwrites a memory location with the given value without reading or
157 /// dropping the old value.
161 /// This operation is marked unsafe because it accepts a raw pointer.
163 /// It does not drop the contents of `dst`. This is safe, but it could leak
164 /// allocations or resources, so care must be taken not to overwrite an object
165 /// that should be dropped.
167 /// This is appropriate for initializing uninitialized memory, or overwriting
168 /// memory that has previously been `read` from.
176 /// let y = &mut x as *mut i32;
180 /// std::ptr::write(y, z);
181 /// println!("{}", std::ptr::read(y));
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub unsafe fn write<T>(dst: *mut T, src: T) {
187 intrinsics::move_val_init(&mut *dst, src)
190 /// Performs a volatile read of the value from `src` without moving it. This
191 /// leaves the memory in `src` unchanged.
193 /// Volatile operations are intended to act on I/O memory, and are guaranteed
194 /// to not be elided or reordered by the compiler across other volatile
199 /// Rust does not currently have a rigorously and formally defined memory model,
200 /// so the precise semantics of what "volatile" means here is subject to change
201 /// over time. That being said, the semantics will almost always end up pretty
202 /// similar to [C11's definition of volatile][c11].
204 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
208 /// Beyond accepting a raw pointer, this is unsafe because it semantically
209 /// moves the value out of `src` without preventing further usage of `src`.
210 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
211 /// `src` is not used before the data is overwritten again (e.g. with `write`,
212 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
213 /// because it will attempt to drop the value previously at `*src`.
221 /// let y = &x as *const i32;
223 /// unsafe { println!("{}", std::ptr::read_volatile(y)); }
226 #[stable(feature = "volatile", since = "1.9.0")]
227 pub unsafe fn read_volatile<T>(src: *const T) -> T {
228 intrinsics::volatile_load(src)
231 /// Performs a volatile write of a memory location with the given value without
232 /// reading or dropping the old value.
234 /// Volatile operations are intended to act on I/O memory, and are guaranteed
235 /// to not be elided or reordered by the compiler across other volatile
240 /// Rust does not currently have a rigorously and formally defined memory model,
241 /// so the precise semantics of what "volatile" means here is subject to change
242 /// over time. That being said, the semantics will almost always end up pretty
243 /// similar to [C11's definition of volatile][c11].
245 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
249 /// This operation is marked unsafe because it accepts a raw pointer.
251 /// It does not drop the contents of `dst`. This is safe, but it could leak
252 /// allocations or resources, so care must be taken not to overwrite an object
253 /// that should be dropped.
255 /// This is appropriate for initializing uninitialized memory, or overwriting
256 /// memory that has previously been `read` from.
264 /// let y = &mut x as *mut i32;
268 /// std::ptr::write_volatile(y, z);
269 /// println!("{}", std::ptr::read_volatile(y));
273 #[stable(feature = "volatile", since = "1.9.0")]
274 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
275 intrinsics::volatile_store(dst, src);
278 #[lang = "const_ptr"]
279 impl<T: ?Sized> *const T {
280 /// Returns true if the pointer is null.
287 /// let s: &str = "Follow the rabbit";
288 /// let ptr: *const u8 = s.as_ptr();
289 /// assert!(!ptr.is_null());
291 #[stable(feature = "rust1", since = "1.0.0")]
293 pub fn is_null(self) -> bool where T: Sized {
297 /// Returns `None` if the pointer is null, or else returns a reference to
298 /// the value wrapped in `Some`.
302 /// While this method and its mutable counterpart are useful for
303 /// null-safety, it is important to note that this is still an unsafe
304 /// operation because the returned value could be pointing to invalid
307 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
308 /// not necessarily reflect the actual lifetime of the data.
315 /// let val: *const u8 = &10u8 as *const u8;
318 /// if let Some(val_back) = val.as_ref() {
319 /// println!("We got back the value: {}!", val_back);
323 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
325 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
333 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
334 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
338 /// Both the starting and resulting pointer must be either in bounds or one
339 /// byte past the end of an allocated object. If either pointer is out of
340 /// bounds or arithmetic overflow occurs then
341 /// any further use of the returned value will result in undefined behavior.
348 /// let s: &str = "123";
349 /// let ptr: *const u8 = s.as_ptr();
352 /// println!("{}", *ptr.offset(1) as char);
353 /// println!("{}", *ptr.offset(2) as char);
356 #[stable(feature = "rust1", since = "1.0.0")]
358 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
359 intrinsics::offset(self, count)
364 impl<T: ?Sized> *mut T {
365 /// Returns true if the pointer is null.
372 /// let mut s = [1, 2, 3];
373 /// let ptr: *mut u32 = s.as_mut_ptr();
374 /// assert!(!ptr.is_null());
376 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn is_null(self) -> bool where T: Sized {
382 /// Returns `None` if the pointer is null, or else returns a reference to
383 /// the value wrapped in `Some`.
387 /// While this method and its mutable counterpart are useful for
388 /// null-safety, it is important to note that this is still an unsafe
389 /// operation because the returned value could be pointing to invalid
392 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
393 /// not necessarily reflect the actual lifetime of the data.
400 /// let val: *mut u8 = &mut 10u8 as *mut u8;
403 /// if let Some(val_back) = val.as_ref() {
404 /// println!("We got back the value: {}!", val_back);
408 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
410 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
418 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
419 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
423 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
424 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
425 /// the pointer is used.
432 /// let mut s = [1, 2, 3];
433 /// let ptr: *mut u32 = s.as_mut_ptr();
436 /// println!("{}", *ptr.offset(1));
437 /// println!("{}", *ptr.offset(2));
440 #[stable(feature = "rust1", since = "1.0.0")]
442 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
443 intrinsics::offset(self, count) as *mut T
446 /// Returns `None` if the pointer is null, or else returns a mutable
447 /// reference to the value wrapped in `Some`.
451 /// As with `as_ref`, this is unsafe because it cannot verify the validity
452 /// of the returned pointer, nor can it ensure that the lifetime `'a`
453 /// returned is indeed a valid lifetime for the contained data.
460 /// let mut s = [1, 2, 3];
461 /// let ptr: *mut u32 = s.as_mut_ptr();
462 /// let first_value = unsafe { ptr.as_mut().unwrap() };
463 /// *first_value = 4;
464 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
466 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
468 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
477 // Equality for pointers
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl<T: ?Sized> PartialEq for *const T {
481 fn eq(&self, other: &*const T) -> bool { *self == *other }
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl<T: ?Sized> Eq for *const T {}
487 #[stable(feature = "rust1", since = "1.0.0")]
488 impl<T: ?Sized> PartialEq for *mut T {
490 fn eq(&self, other: &*mut T) -> bool { *self == *other }
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl<T: ?Sized> Eq for *mut T {}
496 #[stable(feature = "rust1", since = "1.0.0")]
497 impl<T: ?Sized> Clone for *const T {
499 fn clone(&self) -> *const T {
504 #[stable(feature = "rust1", since = "1.0.0")]
505 impl<T: ?Sized> Clone for *mut T {
507 fn clone(&self) -> *mut T {
512 // Impls for function pointers
513 macro_rules! fnptr_impls_safety_abi {
514 ($FnTy: ty, $($Arg: ident),*) => {
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl<Ret, $($Arg),*> Clone for $FnTy {
518 fn clone(&self) -> Self {
523 #[stable(feature = "fnptr_impls", since = "1.4.0")]
524 impl<Ret, $($Arg),*> PartialEq for $FnTy {
526 fn eq(&self, other: &Self) -> bool {
527 *self as usize == *other as usize
531 #[stable(feature = "fnptr_impls", since = "1.4.0")]
532 impl<Ret, $($Arg),*> Eq for $FnTy {}
534 #[stable(feature = "fnptr_impls", since = "1.4.0")]
535 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
537 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
538 (*self as usize).partial_cmp(&(*other as usize))
542 #[stable(feature = "fnptr_impls", since = "1.4.0")]
543 impl<Ret, $($Arg),*> Ord for $FnTy {
545 fn cmp(&self, other: &Self) -> Ordering {
546 (*self as usize).cmp(&(*other as usize))
550 #[stable(feature = "fnptr_impls", since = "1.4.0")]
551 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
552 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
553 state.write_usize(*self as usize)
557 #[stable(feature = "fnptr_impls", since = "1.4.0")]
558 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
559 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
560 fmt::Pointer::fmt(&(*self as *const ()), f)
564 #[stable(feature = "fnptr_impls", since = "1.4.0")]
565 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
566 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
567 fmt::Pointer::fmt(&(*self as *const ()), f)
573 macro_rules! fnptr_impls_args {
574 ($($Arg: ident),+) => {
575 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
576 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
577 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
578 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
579 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
580 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
583 // No variadic functions with 0 parameters
584 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
585 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
586 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
587 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
591 fnptr_impls_args! { }
592 fnptr_impls_args! { A }
593 fnptr_impls_args! { A, B }
594 fnptr_impls_args! { A, B, C }
595 fnptr_impls_args! { A, B, C, D }
596 fnptr_impls_args! { A, B, C, D, E }
597 fnptr_impls_args! { A, B, C, D, E, F }
598 fnptr_impls_args! { A, B, C, D, E, F, G }
599 fnptr_impls_args! { A, B, C, D, E, F, G, H }
600 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
601 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
602 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
603 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
605 // Comparison for pointers
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl<T: ?Sized> Ord for *const T {
609 fn cmp(&self, other: &*const T) -> Ordering {
612 } else if self == other {
620 #[stable(feature = "rust1", since = "1.0.0")]
621 impl<T: ?Sized> PartialOrd for *const T {
623 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
624 Some(self.cmp(other))
628 fn lt(&self, other: &*const T) -> bool { *self < *other }
631 fn le(&self, other: &*const T) -> bool { *self <= *other }
634 fn gt(&self, other: &*const T) -> bool { *self > *other }
637 fn ge(&self, other: &*const T) -> bool { *self >= *other }
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl<T: ?Sized> Ord for *mut T {
643 fn cmp(&self, other: &*mut T) -> Ordering {
646 } else if self == other {
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl<T: ?Sized> PartialOrd for *mut T {
657 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
658 Some(self.cmp(other))
662 fn lt(&self, other: &*mut T) -> bool { *self < *other }
665 fn le(&self, other: &*mut T) -> bool { *self <= *other }
668 fn gt(&self, other: &*mut T) -> bool { *self > *other }
671 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
674 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
675 /// of this wrapper owns the referent. This in turn implies that the
676 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
677 /// `*mut T` (which conveys no particular ownership semantics). It
678 /// also implies that the referent of the pointer should not be
679 /// modified without a unique path to the `Unique` reference. Useful
680 /// for building abstractions like `Vec<T>` or `Box<T>`, which
681 /// internally use raw pointers to manage the memory that they own.
682 #[allow(missing_debug_implementations)]
683 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
685 pub struct Unique<T: ?Sized> {
686 pointer: NonZero<*const T>,
687 // NOTE: this marker has no consequences for variance, but is necessary
688 // for dropck to understand that we logically own a `T`.
691 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
692 _marker: PhantomData<T>,
695 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
696 /// reference is unaliased. Note that this aliasing invariant is
697 /// unenforced by the type system; the abstraction using the
698 /// `Unique` must enforce it.
699 #[unstable(feature = "unique", issue = "27730")]
700 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
702 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
703 /// reference is unaliased. Note that this aliasing invariant is
704 /// unenforced by the type system; the abstraction using the
705 /// `Unique` must enforce it.
706 #[unstable(feature = "unique", issue = "27730")]
707 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
709 #[unstable(feature = "unique", issue = "27730")]
710 impl<T: ?Sized> Unique<T> {
711 /// Creates a new `Unique`.
715 /// `ptr` must be non-null.
716 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
717 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
720 /// Dereferences the content.
721 pub unsafe fn get(&self) -> &T {
725 /// Mutably dereferences the content.
726 pub unsafe fn get_mut(&mut self) -> &mut T {
731 #[unstable(feature = "unique", issue = "27730")]
732 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
734 #[unstable(feature = "unique", issue= "27730")]
735 impl<T:?Sized> Deref for Unique<T> {
736 type Target = *mut T;
739 fn deref(&self) -> &*mut T {
740 unsafe { mem::transmute(&*self.pointer) }
744 #[stable(feature = "rust1", since = "1.0.0")]
745 impl<T> fmt::Pointer for Unique<T> {
746 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
747 fmt::Pointer::fmt(&*self.pointer, f)
751 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
752 /// of this wrapper has shared ownership of the referent. Useful for
753 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
754 /// use raw pointers to manage the memory that they own.
755 #[allow(missing_debug_implementations)]
756 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
758 pub struct Shared<T: ?Sized> {
759 pointer: NonZero<*const T>,
760 // NOTE: this marker has no consequences for variance, but is necessary
761 // for dropck to understand that we logically own a `T`.
764 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
765 _marker: PhantomData<T>,
768 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
769 // NB: This impl is unnecessary, but should provide better error messages.
770 #[unstable(feature = "shared", issue = "27730")]
771 impl<T: ?Sized> !Send for Shared<T> { }
773 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
774 // NB: This impl is unnecessary, but should provide better error messages.
775 #[unstable(feature = "shared", issue = "27730")]
776 impl<T: ?Sized> !Sync for Shared<T> { }
778 #[unstable(feature = "shared", issue = "27730")]
779 impl<T: ?Sized> Shared<T> {
780 /// Creates a new `Shared`.
784 /// `ptr` must be non-null.
785 pub unsafe fn new(ptr: *mut T) -> Self {
786 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
790 #[unstable(feature = "shared", issue = "27730")]
791 impl<T: ?Sized> Clone for Shared<T> {
792 fn clone(&self) -> Self {
797 #[unstable(feature = "shared", issue = "27730")]
798 impl<T: ?Sized> Copy for Shared<T> { }
800 #[unstable(feature = "shared", issue = "27730")]
801 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
803 #[unstable(feature = "shared", issue = "27730")]
804 impl<T: ?Sized> Deref for Shared<T> {
805 type Target = *mut T;
808 fn deref(&self) -> &*mut T {
809 unsafe { mem::transmute(&*self.pointer) }
813 #[unstable(feature = "shared", issue = "27730")]
814 impl<T> fmt::Pointer for Shared<T> {
815 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
816 fmt::Pointer::fmt(&*self.pointer, f)