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;
132 /// assert_eq!(std::ptr::read(y), 12);
136 #[stable(feature = "rust1", since = "1.0.0")]
137 pub unsafe fn read<T>(src: *const T) -> T {
138 let mut tmp: T = mem::uninitialized();
139 copy_nonoverlapping(src, &mut tmp, 1);
143 #[allow(missing_docs)]
145 #[unstable(feature = "filling_drop",
146 reason = "may play a larger role in std::ptr future extensions",
148 pub unsafe fn read_and_drop<T>(dest: *mut T) -> T {
149 // Copy the data out from `dest`:
150 let tmp = read(&*dest);
152 // Now mark `dest` as dropped:
153 write_bytes(dest, mem::POST_DROP_U8, 1);
158 /// Overwrites a memory location with the given value without reading or
159 /// dropping the old value.
163 /// This operation is marked unsafe because it accepts a raw pointer.
165 /// It does not drop the contents of `dst`. This is safe, but it could leak
166 /// allocations or resources, so care must be taken not to overwrite an object
167 /// that should be dropped.
169 /// This is appropriate for initializing uninitialized memory, or overwriting
170 /// memory that has previously been `read` from.
178 /// let y = &mut x as *mut i32;
182 /// std::ptr::write(y, z);
183 /// assert_eq!(std::ptr::read(y), 12);
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub unsafe fn write<T>(dst: *mut T, src: T) {
189 intrinsics::move_val_init(&mut *dst, src)
192 /// Performs a volatile read of the value from `src` without moving it. This
193 /// leaves the memory in `src` unchanged.
195 /// Volatile operations are intended to act on I/O memory, and are guaranteed
196 /// to not be elided or reordered by the compiler across other volatile
201 /// Rust does not currently have a rigorously and formally defined memory model,
202 /// so the precise semantics of what "volatile" means here is subject to change
203 /// over time. That being said, the semantics will almost always end up pretty
204 /// similar to [C11's definition of volatile][c11].
206 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
210 /// Beyond accepting a raw pointer, this is unsafe because it semantically
211 /// moves the value out of `src` without preventing further usage of `src`.
212 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
213 /// `src` is not used before the data is overwritten again (e.g. with `write`,
214 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
215 /// because it will attempt to drop the value previously at `*src`.
223 /// let y = &x as *const i32;
226 /// assert_eq!(std::ptr::read_volatile(y), 12);
230 #[stable(feature = "volatile", since = "1.9.0")]
231 pub unsafe fn read_volatile<T>(src: *const T) -> T {
232 intrinsics::volatile_load(src)
235 /// Performs a volatile write of a memory location with the given value without
236 /// reading or dropping the old value.
238 /// Volatile operations are intended to act on I/O memory, and are guaranteed
239 /// to not be elided or reordered by the compiler across other volatile
244 /// Rust does not currently have a rigorously and formally defined memory model,
245 /// so the precise semantics of what "volatile" means here is subject to change
246 /// over time. That being said, the semantics will almost always end up pretty
247 /// similar to [C11's definition of volatile][c11].
249 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
253 /// This operation is marked unsafe because it accepts a raw pointer.
255 /// It does not drop the contents of `dst`. This is safe, but it could leak
256 /// allocations or resources, so care must be taken not to overwrite an object
257 /// that should be dropped.
259 /// This is appropriate for initializing uninitialized memory, or overwriting
260 /// memory that has previously been `read` from.
268 /// let y = &mut x as *mut i32;
272 /// std::ptr::write_volatile(y, z);
273 /// assert_eq!(std::ptr::read_volatile(y), 12);
277 #[stable(feature = "volatile", since = "1.9.0")]
278 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
279 intrinsics::volatile_store(dst, src);
282 #[lang = "const_ptr"]
283 impl<T: ?Sized> *const T {
284 /// Returns true if the pointer is null.
291 /// let s: &str = "Follow the rabbit";
292 /// let ptr: *const u8 = s.as_ptr();
293 /// assert!(!ptr.is_null());
295 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn is_null(self) -> bool where T: Sized {
301 /// Returns `None` if the pointer is null, or else returns a reference to
302 /// the value wrapped in `Some`.
306 /// While this method and its mutable counterpart are useful for
307 /// null-safety, it is important to note that this is still an unsafe
308 /// operation because the returned value could be pointing to invalid
311 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
312 /// not necessarily reflect the actual lifetime of the data.
319 /// let val: *const u8 = &10u8 as *const u8;
322 /// if let Some(val_back) = val.as_ref() {
323 /// println!("We got back the value: {}!", val_back);
327 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
329 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
337 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
338 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
342 /// Both the starting and resulting pointer must be either in bounds or one
343 /// byte past the end of an allocated object. If either pointer is out of
344 /// bounds or arithmetic overflow occurs then
345 /// any further use of the returned value will result in undefined behavior.
352 /// let s: &str = "123";
353 /// let ptr: *const u8 = s.as_ptr();
356 /// println!("{}", *ptr.offset(1) as char);
357 /// println!("{}", *ptr.offset(2) as char);
360 #[stable(feature = "rust1", since = "1.0.0")]
362 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
363 intrinsics::offset(self, count)
368 impl<T: ?Sized> *mut T {
369 /// Returns true if the pointer is null.
376 /// let mut s = [1, 2, 3];
377 /// let ptr: *mut u32 = s.as_mut_ptr();
378 /// assert!(!ptr.is_null());
380 #[stable(feature = "rust1", since = "1.0.0")]
382 pub fn is_null(self) -> bool where T: Sized {
386 /// Returns `None` if the pointer is null, or else returns a reference to
387 /// the value wrapped in `Some`.
391 /// While this method and its mutable counterpart are useful for
392 /// null-safety, it is important to note that this is still an unsafe
393 /// operation because the returned value could be pointing to invalid
396 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
397 /// not necessarily reflect the actual lifetime of the data.
404 /// let val: *mut u8 = &mut 10u8 as *mut u8;
407 /// if let Some(val_back) = val.as_ref() {
408 /// println!("We got back the value: {}!", val_back);
412 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
414 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
422 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
423 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
427 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
428 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
429 /// the pointer is used.
436 /// let mut s = [1, 2, 3];
437 /// let ptr: *mut u32 = s.as_mut_ptr();
440 /// println!("{}", *ptr.offset(1));
441 /// println!("{}", *ptr.offset(2));
444 #[stable(feature = "rust1", since = "1.0.0")]
446 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
447 intrinsics::offset(self, count) as *mut T
450 /// Returns `None` if the pointer is null, or else returns a mutable
451 /// reference to the value wrapped in `Some`.
455 /// As with `as_ref`, this is unsafe because it cannot verify the validity
456 /// of the returned pointer, nor can it ensure that the lifetime `'a`
457 /// returned is indeed a valid lifetime for the contained data.
464 /// let mut s = [1, 2, 3];
465 /// let ptr: *mut u32 = s.as_mut_ptr();
466 /// let first_value = unsafe { ptr.as_mut().unwrap() };
467 /// *first_value = 4;
468 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
470 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
472 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
481 // Equality for pointers
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl<T: ?Sized> PartialEq for *const T {
485 fn eq(&self, other: &*const T) -> bool { *self == *other }
488 #[stable(feature = "rust1", since = "1.0.0")]
489 impl<T: ?Sized> Eq for *const T {}
491 #[stable(feature = "rust1", since = "1.0.0")]
492 impl<T: ?Sized> PartialEq for *mut T {
494 fn eq(&self, other: &*mut T) -> bool { *self == *other }
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<T: ?Sized> Eq for *mut T {}
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl<T: ?Sized> Clone for *const T {
503 fn clone(&self) -> *const T {
508 #[stable(feature = "rust1", since = "1.0.0")]
509 impl<T: ?Sized> Clone for *mut T {
511 fn clone(&self) -> *mut T {
516 // Impls for function pointers
517 macro_rules! fnptr_impls_safety_abi {
518 ($FnTy: ty, $($Arg: ident),*) => {
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl<Ret, $($Arg),*> Clone for $FnTy {
522 fn clone(&self) -> Self {
527 #[stable(feature = "fnptr_impls", since = "1.4.0")]
528 impl<Ret, $($Arg),*> PartialEq for $FnTy {
530 fn eq(&self, other: &Self) -> bool {
531 *self as usize == *other as usize
535 #[stable(feature = "fnptr_impls", since = "1.4.0")]
536 impl<Ret, $($Arg),*> Eq for $FnTy {}
538 #[stable(feature = "fnptr_impls", since = "1.4.0")]
539 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
541 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
542 (*self as usize).partial_cmp(&(*other as usize))
546 #[stable(feature = "fnptr_impls", since = "1.4.0")]
547 impl<Ret, $($Arg),*> Ord for $FnTy {
549 fn cmp(&self, other: &Self) -> Ordering {
550 (*self as usize).cmp(&(*other as usize))
554 #[stable(feature = "fnptr_impls", since = "1.4.0")]
555 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
556 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
557 state.write_usize(*self as usize)
561 #[stable(feature = "fnptr_impls", since = "1.4.0")]
562 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
563 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
564 fmt::Pointer::fmt(&(*self as *const ()), f)
568 #[stable(feature = "fnptr_impls", since = "1.4.0")]
569 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
570 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
571 fmt::Pointer::fmt(&(*self as *const ()), f)
577 macro_rules! fnptr_impls_args {
578 ($($Arg: ident),+) => {
579 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
580 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
581 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
582 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
583 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
584 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
587 // No variadic functions with 0 parameters
588 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
589 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
590 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
591 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
595 fnptr_impls_args! { }
596 fnptr_impls_args! { A }
597 fnptr_impls_args! { A, B }
598 fnptr_impls_args! { A, B, C }
599 fnptr_impls_args! { A, B, C, D }
600 fnptr_impls_args! { A, B, C, D, E }
601 fnptr_impls_args! { A, B, C, D, E, F }
602 fnptr_impls_args! { A, B, C, D, E, F, G }
603 fnptr_impls_args! { A, B, C, D, E, F, G, H }
604 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
605 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
606 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
607 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
609 // Comparison for pointers
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl<T: ?Sized> Ord for *const T {
613 fn cmp(&self, other: &*const T) -> Ordering {
616 } else if self == other {
624 #[stable(feature = "rust1", since = "1.0.0")]
625 impl<T: ?Sized> PartialOrd for *const T {
627 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
628 Some(self.cmp(other))
632 fn lt(&self, other: &*const T) -> bool { *self < *other }
635 fn le(&self, other: &*const T) -> bool { *self <= *other }
638 fn gt(&self, other: &*const T) -> bool { *self > *other }
641 fn ge(&self, other: &*const T) -> bool { *self >= *other }
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl<T: ?Sized> Ord for *mut T {
647 fn cmp(&self, other: &*mut T) -> Ordering {
650 } else if self == other {
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<T: ?Sized> PartialOrd for *mut T {
661 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
662 Some(self.cmp(other))
666 fn lt(&self, other: &*mut T) -> bool { *self < *other }
669 fn le(&self, other: &*mut T) -> bool { *self <= *other }
672 fn gt(&self, other: &*mut T) -> bool { *self > *other }
675 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
678 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
679 /// of this wrapper owns the referent. This in turn implies that the
680 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
681 /// `*mut T` (which conveys no particular ownership semantics). It
682 /// also implies that the referent of the pointer should not be
683 /// modified without a unique path to the `Unique` reference. Useful
684 /// for building abstractions like `Vec<T>` or `Box<T>`, which
685 /// internally use raw pointers to manage the memory that they own.
686 #[allow(missing_debug_implementations)]
687 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
689 pub struct Unique<T: ?Sized> {
690 pointer: NonZero<*const T>,
691 // NOTE: this marker has no consequences for variance, but is necessary
692 // for dropck to understand that we logically own a `T`.
695 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
696 _marker: PhantomData<T>,
699 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
700 /// reference is unaliased. Note that this aliasing invariant is
701 /// unenforced by the type system; the abstraction using the
702 /// `Unique` must enforce it.
703 #[unstable(feature = "unique", issue = "27730")]
704 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
706 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
707 /// reference is unaliased. Note that this aliasing invariant is
708 /// unenforced by the type system; the abstraction using the
709 /// `Unique` must enforce it.
710 #[unstable(feature = "unique", issue = "27730")]
711 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
713 #[unstable(feature = "unique", issue = "27730")]
714 impl<T: ?Sized> Unique<T> {
715 /// Creates a new `Unique`.
719 /// `ptr` must be non-null.
720 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
721 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
724 /// Dereferences the content.
725 pub unsafe fn get(&self) -> &T {
729 /// Mutably dereferences the content.
730 pub unsafe fn get_mut(&mut self) -> &mut T {
735 #[unstable(feature = "unique", issue = "27730")]
736 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
738 #[unstable(feature = "unique", issue= "27730")]
739 impl<T:?Sized> Deref for Unique<T> {
740 type Target = *mut T;
743 fn deref(&self) -> &*mut T {
744 unsafe { mem::transmute(&*self.pointer) }
748 #[stable(feature = "rust1", since = "1.0.0")]
749 impl<T> fmt::Pointer for Unique<T> {
750 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
751 fmt::Pointer::fmt(&*self.pointer, f)
755 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
756 /// of this wrapper has shared ownership of the referent. Useful for
757 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
758 /// use raw pointers to manage the memory that they own.
759 #[allow(missing_debug_implementations)]
760 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
762 pub struct Shared<T: ?Sized> {
763 pointer: NonZero<*const T>,
764 // NOTE: this marker has no consequences for variance, but is necessary
765 // for dropck to understand that we logically own a `T`.
768 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
769 _marker: PhantomData<T>,
772 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
773 // NB: This impl is unnecessary, but should provide better error messages.
774 #[unstable(feature = "shared", issue = "27730")]
775 impl<T: ?Sized> !Send for Shared<T> { }
777 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
778 // NB: This impl is unnecessary, but should provide better error messages.
779 #[unstable(feature = "shared", issue = "27730")]
780 impl<T: ?Sized> !Sync for Shared<T> { }
782 #[unstable(feature = "shared", issue = "27730")]
783 impl<T: ?Sized> Shared<T> {
784 /// Creates a new `Shared`.
788 /// `ptr` must be non-null.
789 pub unsafe fn new(ptr: *mut T) -> Self {
790 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
794 #[unstable(feature = "shared", issue = "27730")]
795 impl<T: ?Sized> Clone for Shared<T> {
796 fn clone(&self) -> Self {
801 #[unstable(feature = "shared", issue = "27730")]
802 impl<T: ?Sized> Copy for Shared<T> { }
804 #[unstable(feature = "shared", issue = "27730")]
805 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
807 #[unstable(feature = "shared", issue = "27730")]
808 impl<T: ?Sized> Deref for Shared<T> {
809 type Target = *mut T;
812 fn deref(&self) -> &*mut T {
813 unsafe { mem::transmute(&*self.pointer) }
817 #[unstable(feature = "shared", issue = "27730")]
818 impl<T> fmt::Pointer for Shared<T> {
819 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
820 fmt::Pointer::fmt(&*self.pointer, f)