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 /// Overwrites a memory location with the given value without reading or
144 /// dropping the old value.
148 /// This operation is marked unsafe because it accepts a raw pointer.
150 /// It does not drop the contents of `dst`. This is safe, but it could leak
151 /// allocations or resources, so care must be taken not to overwrite an object
152 /// that should be dropped.
154 /// This is appropriate for initializing uninitialized memory, or overwriting
155 /// memory that has previously been `read` from.
163 /// let y = &mut x as *mut i32;
167 /// std::ptr::write(y, z);
168 /// assert_eq!(std::ptr::read(y), 12);
172 #[stable(feature = "rust1", since = "1.0.0")]
173 pub unsafe fn write<T>(dst: *mut T, src: T) {
174 intrinsics::move_val_init(&mut *dst, src)
177 /// Performs a volatile read of the value from `src` without moving it. This
178 /// leaves the memory in `src` unchanged.
180 /// Volatile operations are intended to act on I/O memory, and are guaranteed
181 /// to not be elided or reordered by the compiler across other volatile
186 /// Rust does not currently have a rigorously and formally defined memory model,
187 /// so the precise semantics of what "volatile" means here is subject to change
188 /// over time. That being said, the semantics will almost always end up pretty
189 /// similar to [C11's definition of volatile][c11].
191 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
195 /// Beyond accepting a raw pointer, this is unsafe because it semantically
196 /// moves the value out of `src` without preventing further usage of `src`.
197 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
198 /// `src` is not used before the data is overwritten again (e.g. with `write`,
199 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
200 /// because it will attempt to drop the value previously at `*src`.
208 /// let y = &x as *const i32;
211 /// assert_eq!(std::ptr::read_volatile(y), 12);
215 #[stable(feature = "volatile", since = "1.9.0")]
216 pub unsafe fn read_volatile<T>(src: *const T) -> T {
217 intrinsics::volatile_load(src)
220 /// Performs a volatile write of a memory location with the given value without
221 /// reading or dropping the old value.
223 /// Volatile operations are intended to act on I/O memory, and are guaranteed
224 /// to not be elided or reordered by the compiler across other volatile
229 /// Rust does not currently have a rigorously and formally defined memory model,
230 /// so the precise semantics of what "volatile" means here is subject to change
231 /// over time. That being said, the semantics will almost always end up pretty
232 /// similar to [C11's definition of volatile][c11].
234 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
238 /// This operation is marked unsafe because it accepts a raw pointer.
240 /// It does not drop the contents of `dst`. This is safe, but it could leak
241 /// allocations or resources, so care must be taken not to overwrite an object
242 /// that should be dropped.
244 /// This is appropriate for initializing uninitialized memory, or overwriting
245 /// memory that has previously been `read` from.
253 /// let y = &mut x as *mut i32;
257 /// std::ptr::write_volatile(y, z);
258 /// assert_eq!(std::ptr::read_volatile(y), 12);
262 #[stable(feature = "volatile", since = "1.9.0")]
263 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
264 intrinsics::volatile_store(dst, src);
267 #[lang = "const_ptr"]
268 impl<T: ?Sized> *const T {
269 /// Returns true if the pointer is null.
276 /// let s: &str = "Follow the rabbit";
277 /// let ptr: *const u8 = s.as_ptr();
278 /// assert!(!ptr.is_null());
280 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn is_null(self) -> bool where T: Sized {
286 /// Returns `None` if the pointer is null, or else returns a reference to
287 /// the value wrapped in `Some`.
291 /// While this method and its mutable counterpart are useful for
292 /// null-safety, it is important to note that this is still an unsafe
293 /// operation because the returned value could be pointing to invalid
296 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
297 /// not necessarily reflect the actual lifetime of the data.
304 /// let val: *const u8 = &10u8 as *const u8;
307 /// if let Some(val_back) = val.as_ref() {
308 /// println!("We got back the value: {}!", val_back);
312 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
314 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
322 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
323 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
327 /// Both the starting and resulting pointer must be either in bounds or one
328 /// byte past the end of an allocated object. If either pointer is out of
329 /// bounds or arithmetic overflow occurs then
330 /// any further use of the returned value will result in undefined behavior.
337 /// let s: &str = "123";
338 /// let ptr: *const u8 = s.as_ptr();
341 /// println!("{}", *ptr.offset(1) as char);
342 /// println!("{}", *ptr.offset(2) as char);
345 #[stable(feature = "rust1", since = "1.0.0")]
347 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
348 intrinsics::offset(self, count)
353 impl<T: ?Sized> *mut T {
354 /// Returns true if the pointer is null.
361 /// let mut s = [1, 2, 3];
362 /// let ptr: *mut u32 = s.as_mut_ptr();
363 /// assert!(!ptr.is_null());
365 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn is_null(self) -> bool where T: Sized {
371 /// Returns `None` if the pointer is null, or else returns a reference to
372 /// the value wrapped in `Some`.
376 /// While this method and its mutable counterpart are useful for
377 /// null-safety, it is important to note that this is still an unsafe
378 /// operation because the returned value could be pointing to invalid
381 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
382 /// not necessarily reflect the actual lifetime of the data.
389 /// let val: *mut u8 = &mut 10u8 as *mut u8;
392 /// if let Some(val_back) = val.as_ref() {
393 /// println!("We got back the value: {}!", val_back);
397 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
399 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
407 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
408 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
412 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
413 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
414 /// the pointer is used.
421 /// let mut s = [1, 2, 3];
422 /// let ptr: *mut u32 = s.as_mut_ptr();
425 /// println!("{}", *ptr.offset(1));
426 /// println!("{}", *ptr.offset(2));
429 #[stable(feature = "rust1", since = "1.0.0")]
431 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
432 intrinsics::offset(self, count) as *mut T
435 /// Returns `None` if the pointer is null, or else returns a mutable
436 /// reference to the value wrapped in `Some`.
440 /// As with `as_ref`, this is unsafe because it cannot verify the validity
441 /// of the returned pointer, nor can it ensure that the lifetime `'a`
442 /// returned is indeed a valid lifetime for the contained data.
449 /// let mut s = [1, 2, 3];
450 /// let ptr: *mut u32 = s.as_mut_ptr();
451 /// let first_value = unsafe { ptr.as_mut().unwrap() };
452 /// *first_value = 4;
453 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
455 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
457 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
466 // Equality for pointers
467 #[stable(feature = "rust1", since = "1.0.0")]
468 impl<T: ?Sized> PartialEq for *const T {
470 fn eq(&self, other: &*const T) -> bool { *self == *other }
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl<T: ?Sized> Eq for *const T {}
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl<T: ?Sized> PartialEq for *mut T {
479 fn eq(&self, other: &*mut T) -> bool { *self == *other }
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl<T: ?Sized> Eq for *mut T {}
485 #[stable(feature = "rust1", since = "1.0.0")]
486 impl<T: ?Sized> Clone for *const T {
488 fn clone(&self) -> *const T {
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl<T: ?Sized> Clone for *mut T {
496 fn clone(&self) -> *mut T {
501 // Impls for function pointers
502 macro_rules! fnptr_impls_safety_abi {
503 ($FnTy: ty, $($Arg: ident),*) => {
504 #[stable(feature = "rust1", since = "1.0.0")]
505 impl<Ret, $($Arg),*> Clone for $FnTy {
507 fn clone(&self) -> Self {
512 #[stable(feature = "fnptr_impls", since = "1.4.0")]
513 impl<Ret, $($Arg),*> PartialEq for $FnTy {
515 fn eq(&self, other: &Self) -> bool {
516 *self as usize == *other as usize
520 #[stable(feature = "fnptr_impls", since = "1.4.0")]
521 impl<Ret, $($Arg),*> Eq for $FnTy {}
523 #[stable(feature = "fnptr_impls", since = "1.4.0")]
524 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
526 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
527 (*self as usize).partial_cmp(&(*other as usize))
531 #[stable(feature = "fnptr_impls", since = "1.4.0")]
532 impl<Ret, $($Arg),*> Ord for $FnTy {
534 fn cmp(&self, other: &Self) -> Ordering {
535 (*self as usize).cmp(&(*other as usize))
539 #[stable(feature = "fnptr_impls", since = "1.4.0")]
540 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
541 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
542 state.write_usize(*self as usize)
546 #[stable(feature = "fnptr_impls", since = "1.4.0")]
547 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
548 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549 fmt::Pointer::fmt(&(*self as *const ()), f)
553 #[stable(feature = "fnptr_impls", since = "1.4.0")]
554 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
555 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
556 fmt::Pointer::fmt(&(*self as *const ()), f)
562 macro_rules! fnptr_impls_args {
563 ($($Arg: ident),+) => {
564 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
565 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
566 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
567 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
568 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
569 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
572 // No variadic functions with 0 parameters
573 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
574 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
575 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
576 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
580 fnptr_impls_args! { }
581 fnptr_impls_args! { A }
582 fnptr_impls_args! { A, B }
583 fnptr_impls_args! { A, B, C }
584 fnptr_impls_args! { A, B, C, D }
585 fnptr_impls_args! { A, B, C, D, E }
586 fnptr_impls_args! { A, B, C, D, E, F }
587 fnptr_impls_args! { A, B, C, D, E, F, G }
588 fnptr_impls_args! { A, B, C, D, E, F, G, H }
589 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
590 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
591 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
592 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
594 // Comparison for pointers
595 #[stable(feature = "rust1", since = "1.0.0")]
596 impl<T: ?Sized> Ord for *const T {
598 fn cmp(&self, other: &*const T) -> Ordering {
601 } else if self == other {
609 #[stable(feature = "rust1", since = "1.0.0")]
610 impl<T: ?Sized> PartialOrd for *const T {
612 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
613 Some(self.cmp(other))
617 fn lt(&self, other: &*const T) -> bool { *self < *other }
620 fn le(&self, other: &*const T) -> bool { *self <= *other }
623 fn gt(&self, other: &*const T) -> bool { *self > *other }
626 fn ge(&self, other: &*const T) -> bool { *self >= *other }
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<T: ?Sized> Ord for *mut T {
632 fn cmp(&self, other: &*mut T) -> Ordering {
635 } else if self == other {
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl<T: ?Sized> PartialOrd for *mut T {
646 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
647 Some(self.cmp(other))
651 fn lt(&self, other: &*mut T) -> bool { *self < *other }
654 fn le(&self, other: &*mut T) -> bool { *self <= *other }
657 fn gt(&self, other: &*mut T) -> bool { *self > *other }
660 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
663 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
664 /// of this wrapper owns the referent. This in turn implies that the
665 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
666 /// `*mut T` (which conveys no particular ownership semantics). It
667 /// also implies that the referent of the pointer should not be
668 /// modified without a unique path to the `Unique` reference. Useful
669 /// for building abstractions like `Vec<T>` or `Box<T>`, which
670 /// internally use raw pointers to manage the memory that they own.
671 #[allow(missing_debug_implementations)]
672 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
674 pub struct Unique<T: ?Sized> {
675 pointer: NonZero<*const T>,
676 // NOTE: this marker has no consequences for variance, but is necessary
677 // for dropck to understand that we logically own a `T`.
680 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
681 _marker: PhantomData<T>,
684 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
685 /// reference is unaliased. Note that this aliasing invariant is
686 /// unenforced by the type system; the abstraction using the
687 /// `Unique` must enforce it.
688 #[unstable(feature = "unique", issue = "27730")]
689 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
691 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
692 /// reference is unaliased. Note that this aliasing invariant is
693 /// unenforced by the type system; the abstraction using the
694 /// `Unique` must enforce it.
695 #[unstable(feature = "unique", issue = "27730")]
696 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
698 #[unstable(feature = "unique", issue = "27730")]
699 impl<T: ?Sized> Unique<T> {
700 /// Creates a new `Unique`.
704 /// `ptr` must be non-null.
705 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
706 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
709 /// Dereferences the content.
710 pub unsafe fn get(&self) -> &T {
714 /// Mutably dereferences the content.
715 pub unsafe fn get_mut(&mut self) -> &mut T {
720 #[unstable(feature = "unique", issue = "27730")]
721 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
723 #[unstable(feature = "unique", issue= "27730")]
724 impl<T:?Sized> Deref for Unique<T> {
725 type Target = *mut T;
728 fn deref(&self) -> &*mut T {
729 unsafe { mem::transmute(&*self.pointer) }
733 #[stable(feature = "rust1", since = "1.0.0")]
734 impl<T> fmt::Pointer for Unique<T> {
735 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
736 fmt::Pointer::fmt(&*self.pointer, f)
740 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
741 /// of this wrapper has shared ownership of the referent. Useful for
742 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
743 /// use raw pointers to manage the memory that they own.
744 #[allow(missing_debug_implementations)]
745 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
747 pub struct Shared<T: ?Sized> {
748 pointer: NonZero<*const T>,
749 // NOTE: this marker has no consequences for variance, but is necessary
750 // for dropck to understand that we logically own a `T`.
753 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
754 _marker: PhantomData<T>,
757 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
758 // NB: This impl is unnecessary, but should provide better error messages.
759 #[unstable(feature = "shared", issue = "27730")]
760 impl<T: ?Sized> !Send for Shared<T> { }
762 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
763 // NB: This impl is unnecessary, but should provide better error messages.
764 #[unstable(feature = "shared", issue = "27730")]
765 impl<T: ?Sized> !Sync for Shared<T> { }
767 #[unstable(feature = "shared", issue = "27730")]
768 impl<T: ?Sized> Shared<T> {
769 /// Creates a new `Shared`.
773 /// `ptr` must be non-null.
774 pub unsafe fn new(ptr: *mut T) -> Self {
775 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
779 #[unstable(feature = "shared", issue = "27730")]
780 impl<T: ?Sized> Clone for Shared<T> {
781 fn clone(&self) -> Self {
786 #[unstable(feature = "shared", issue = "27730")]
787 impl<T: ?Sized> Copy for Shared<T> { }
789 #[unstable(feature = "shared", issue = "27730")]
790 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
792 #[unstable(feature = "shared", issue = "27730")]
793 impl<T: ?Sized> Deref for Shared<T> {
794 type Target = *mut T;
797 fn deref(&self) -> &*mut T {
798 unsafe { mem::transmute(&*self.pointer) }
802 #[unstable(feature = "shared", issue = "27730")]
803 impl<T> fmt::Pointer for Shared<T> {
804 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
805 fmt::Pointer::fmt(&*self.pointer, f)