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 is only unsafe because it accepts a raw pointer.
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
81 // Give ourselves some scratch space to work with
82 let mut tmp: T = mem::uninitialized();
85 copy_nonoverlapping(x, &mut tmp, 1);
86 copy(y, x, 1); // `x` and `y` may overlap
87 copy_nonoverlapping(&tmp, y, 1);
89 // y and t now point to the same thing, but we need to completely forget `tmp`
90 // because it's no longer relevant.
94 /// Replaces the value at `dest` with `src`, returning the old
95 /// value, without dropping either.
99 /// This is only unsafe because it accepts a raw pointer.
100 /// Otherwise, this operation is identical to `mem::replace`.
102 #[stable(feature = "rust1", since = "1.0.0")]
103 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
104 mem::swap(&mut *dest, &mut src); // cannot overlap
108 /// Reads the value from `src` without moving it. This leaves the
109 /// memory in `src` unchanged.
113 /// Beyond accepting a raw pointer, this is unsafe because it semantically
114 /// moves the value out of `src` without preventing further usage of `src`.
115 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
116 /// `src` is not used before the data is overwritten again (e.g. with `write`,
117 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
118 /// because it will attempt to drop the value previously at `*src`.
126 /// let y = &x as *const i32;
129 /// assert_eq!(std::ptr::read(y), 12);
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub unsafe fn read<T>(src: *const T) -> T {
135 let mut tmp: T = mem::uninitialized();
136 copy_nonoverlapping(src, &mut tmp, 1);
140 /// Overwrites a memory location with the given value without reading or
141 /// dropping the old value.
145 /// This operation is marked unsafe because it accepts a raw pointer.
147 /// It does not drop the contents of `dst`. This is safe, but it could leak
148 /// allocations or resources, so care must be taken not to overwrite an object
149 /// that should be dropped.
151 /// This is appropriate for initializing uninitialized memory, or overwriting
152 /// memory that has previously been `read` from.
160 /// let y = &mut x as *mut i32;
164 /// std::ptr::write(y, z);
165 /// assert_eq!(std::ptr::read(y), 12);
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub unsafe fn write<T>(dst: *mut T, src: T) {
171 intrinsics::move_val_init(&mut *dst, src)
174 /// Performs a volatile read of the value from `src` without moving it. This
175 /// leaves the memory in `src` unchanged.
177 /// Volatile operations are intended to act on I/O memory, and are guaranteed
178 /// to not be elided or reordered by the compiler across other volatile
183 /// Rust does not currently have a rigorously and formally defined memory model,
184 /// so the precise semantics of what "volatile" means here is subject to change
185 /// over time. That being said, the semantics will almost always end up pretty
186 /// similar to [C11's definition of volatile][c11].
188 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
192 /// Beyond accepting a raw pointer, this is unsafe because it semantically
193 /// moves the value out of `src` without preventing further usage of `src`.
194 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
195 /// `src` is not used before the data is overwritten again (e.g. with `write`,
196 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
197 /// because it will attempt to drop the value previously at `*src`.
205 /// let y = &x as *const i32;
208 /// assert_eq!(std::ptr::read_volatile(y), 12);
212 #[stable(feature = "volatile", since = "1.9.0")]
213 pub unsafe fn read_volatile<T>(src: *const T) -> T {
214 intrinsics::volatile_load(src)
217 /// Performs a volatile write of a memory location with the given value without
218 /// reading or dropping the old value.
220 /// Volatile operations are intended to act on I/O memory, and are guaranteed
221 /// to not be elided or reordered by the compiler across other volatile
226 /// Rust does not currently have a rigorously and formally defined memory model,
227 /// so the precise semantics of what "volatile" means here is subject to change
228 /// over time. That being said, the semantics will almost always end up pretty
229 /// similar to [C11's definition of volatile][c11].
231 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
235 /// This operation is marked unsafe because it accepts a raw pointer.
237 /// It does not drop the contents of `dst`. This is safe, but it could leak
238 /// allocations or resources, so care must be taken not to overwrite an object
239 /// that should be dropped.
241 /// This is appropriate for initializing uninitialized memory, or overwriting
242 /// memory that has previously been `read` from.
250 /// let y = &mut x as *mut i32;
254 /// std::ptr::write_volatile(y, z);
255 /// assert_eq!(std::ptr::read_volatile(y), 12);
259 #[stable(feature = "volatile", since = "1.9.0")]
260 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
261 intrinsics::volatile_store(dst, src);
264 #[lang = "const_ptr"]
265 impl<T: ?Sized> *const T {
266 /// Returns true if the pointer is null.
273 /// let s: &str = "Follow the rabbit";
274 /// let ptr: *const u8 = s.as_ptr();
275 /// assert!(!ptr.is_null());
277 #[stable(feature = "rust1", since = "1.0.0")]
279 pub fn is_null(self) -> bool where T: Sized {
283 /// Returns `None` if the pointer is null, or else returns a reference to
284 /// the value wrapped in `Some`.
288 /// While this method and its mutable counterpart are useful for
289 /// null-safety, it is important to note that this is still an unsafe
290 /// operation because the returned value could be pointing to invalid
293 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
294 /// not necessarily reflect the actual lifetime of the data.
301 /// let val: *const u8 = &10u8 as *const u8;
304 /// if let Some(val_back) = val.as_ref() {
305 /// println!("We got back the value: {}!", val_back);
309 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
311 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
319 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
320 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
324 /// Both the starting and resulting pointer must be either in bounds or one
325 /// byte past the end of an allocated object. If either pointer is out of
326 /// bounds or arithmetic overflow occurs then
327 /// any further use of the returned value will result in undefined behavior.
334 /// let s: &str = "123";
335 /// let ptr: *const u8 = s.as_ptr();
338 /// println!("{}", *ptr.offset(1) as char);
339 /// println!("{}", *ptr.offset(2) as char);
342 #[stable(feature = "rust1", since = "1.0.0")]
344 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
345 intrinsics::offset(self, count)
350 impl<T: ?Sized> *mut T {
351 /// Returns true if the pointer is null.
358 /// let mut s = [1, 2, 3];
359 /// let ptr: *mut u32 = s.as_mut_ptr();
360 /// assert!(!ptr.is_null());
362 #[stable(feature = "rust1", since = "1.0.0")]
364 pub fn is_null(self) -> bool where T: Sized {
368 /// Returns `None` if the pointer is null, or else returns a reference to
369 /// the value wrapped in `Some`.
373 /// While this method and its mutable counterpart are useful for
374 /// null-safety, it is important to note that this is still an unsafe
375 /// operation because the returned value could be pointing to invalid
378 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
379 /// not necessarily reflect the actual lifetime of the data.
386 /// let val: *mut u8 = &mut 10u8 as *mut u8;
389 /// if let Some(val_back) = val.as_ref() {
390 /// println!("We got back the value: {}!", val_back);
394 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
396 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
404 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
405 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
409 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
410 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
411 /// the pointer is used.
418 /// let mut s = [1, 2, 3];
419 /// let ptr: *mut u32 = s.as_mut_ptr();
422 /// println!("{}", *ptr.offset(1));
423 /// println!("{}", *ptr.offset(2));
426 #[stable(feature = "rust1", since = "1.0.0")]
428 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
429 intrinsics::offset(self, count) as *mut T
432 /// Returns `None` if the pointer is null, or else returns a mutable
433 /// reference to the value wrapped in `Some`.
437 /// As with `as_ref`, this is unsafe because it cannot verify the validity
438 /// of the returned pointer, nor can it ensure that the lifetime `'a`
439 /// returned is indeed a valid lifetime for the contained data.
446 /// let mut s = [1, 2, 3];
447 /// let ptr: *mut u32 = s.as_mut_ptr();
448 /// let first_value = unsafe { ptr.as_mut().unwrap() };
449 /// *first_value = 4;
450 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
452 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
454 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
463 // Equality for pointers
464 #[stable(feature = "rust1", since = "1.0.0")]
465 impl<T: ?Sized> PartialEq for *const T {
467 fn eq(&self, other: &*const T) -> bool { *self == *other }
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<T: ?Sized> Eq for *const T {}
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl<T: ?Sized> PartialEq for *mut T {
476 fn eq(&self, other: &*mut T) -> bool { *self == *other }
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl<T: ?Sized> Eq for *mut T {}
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl<T: ?Sized> Clone for *const T {
485 fn clone(&self) -> *const T {
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl<T: ?Sized> Clone for *mut T {
493 fn clone(&self) -> *mut T {
498 // Impls for function pointers
499 macro_rules! fnptr_impls_safety_abi {
500 ($FnTy: ty, $($Arg: ident),*) => {
501 #[stable(feature = "rust1", since = "1.0.0")]
502 impl<Ret, $($Arg),*> Clone for $FnTy {
504 fn clone(&self) -> Self {
509 #[stable(feature = "fnptr_impls", since = "1.4.0")]
510 impl<Ret, $($Arg),*> PartialEq for $FnTy {
512 fn eq(&self, other: &Self) -> bool {
513 *self as usize == *other as usize
517 #[stable(feature = "fnptr_impls", since = "1.4.0")]
518 impl<Ret, $($Arg),*> Eq for $FnTy {}
520 #[stable(feature = "fnptr_impls", since = "1.4.0")]
521 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
523 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
524 (*self as usize).partial_cmp(&(*other as usize))
528 #[stable(feature = "fnptr_impls", since = "1.4.0")]
529 impl<Ret, $($Arg),*> Ord for $FnTy {
531 fn cmp(&self, other: &Self) -> Ordering {
532 (*self as usize).cmp(&(*other as usize))
536 #[stable(feature = "fnptr_impls", since = "1.4.0")]
537 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
538 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
539 state.write_usize(*self as usize)
543 #[stable(feature = "fnptr_impls", since = "1.4.0")]
544 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
545 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
546 fmt::Pointer::fmt(&(*self as *const ()), f)
550 #[stable(feature = "fnptr_impls", since = "1.4.0")]
551 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
553 fmt::Pointer::fmt(&(*self as *const ()), f)
559 macro_rules! fnptr_impls_args {
560 ($($Arg: ident),+) => {
561 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
562 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
563 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
564 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
565 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
566 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
569 // No variadic functions with 0 parameters
570 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
571 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
572 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
573 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
577 fnptr_impls_args! { }
578 fnptr_impls_args! { A }
579 fnptr_impls_args! { A, B }
580 fnptr_impls_args! { A, B, C }
581 fnptr_impls_args! { A, B, C, D }
582 fnptr_impls_args! { A, B, C, D, E }
583 fnptr_impls_args! { A, B, C, D, E, F }
584 fnptr_impls_args! { A, B, C, D, E, F, G }
585 fnptr_impls_args! { A, B, C, D, E, F, G, H }
586 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
587 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
588 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
589 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
591 // Comparison for pointers
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl<T: ?Sized> Ord for *const T {
595 fn cmp(&self, other: &*const T) -> Ordering {
598 } else if self == other {
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl<T: ?Sized> PartialOrd for *const T {
609 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
610 Some(self.cmp(other))
614 fn lt(&self, other: &*const T) -> bool { *self < *other }
617 fn le(&self, other: &*const T) -> bool { *self <= *other }
620 fn gt(&self, other: &*const T) -> bool { *self > *other }
623 fn ge(&self, other: &*const T) -> bool { *self >= *other }
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl<T: ?Sized> Ord for *mut T {
629 fn cmp(&self, other: &*mut T) -> Ordering {
632 } else if self == other {
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl<T: ?Sized> PartialOrd for *mut T {
643 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
644 Some(self.cmp(other))
648 fn lt(&self, other: &*mut T) -> bool { *self < *other }
651 fn le(&self, other: &*mut T) -> bool { *self <= *other }
654 fn gt(&self, other: &*mut T) -> bool { *self > *other }
657 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
660 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
661 /// of this wrapper owns the referent. This in turn implies that the
662 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
663 /// `*mut T` (which conveys no particular ownership semantics). It
664 /// also implies that the referent of the pointer should not be
665 /// modified without a unique path to the `Unique` reference. Useful
666 /// for building abstractions like `Vec<T>` or `Box<T>`, which
667 /// internally use raw pointers to manage the memory that they own.
668 #[allow(missing_debug_implementations)]
669 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
671 pub struct Unique<T: ?Sized> {
672 pointer: NonZero<*const T>,
673 // NOTE: this marker has no consequences for variance, but is necessary
674 // for dropck to understand that we logically own a `T`.
677 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
678 _marker: PhantomData<T>,
681 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
682 /// reference is unaliased. Note that this aliasing invariant is
683 /// unenforced by the type system; the abstraction using the
684 /// `Unique` must enforce it.
685 #[unstable(feature = "unique", issue = "27730")]
686 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
688 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
689 /// reference is unaliased. Note that this aliasing invariant is
690 /// unenforced by the type system; the abstraction using the
691 /// `Unique` must enforce it.
692 #[unstable(feature = "unique", issue = "27730")]
693 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
695 #[unstable(feature = "unique", issue = "27730")]
696 impl<T: ?Sized> Unique<T> {
697 /// Creates a new `Unique`.
701 /// `ptr` must be non-null.
702 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
703 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
706 /// Dereferences the content.
707 pub unsafe fn get(&self) -> &T {
711 /// Mutably dereferences the content.
712 pub unsafe fn get_mut(&mut self) -> &mut T {
717 #[unstable(feature = "unique", issue = "27730")]
718 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
720 #[unstable(feature = "unique", issue= "27730")]
721 impl<T:?Sized> Deref for Unique<T> {
722 type Target = *mut T;
725 fn deref(&self) -> &*mut T {
726 unsafe { mem::transmute(&*self.pointer) }
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl<T> fmt::Pointer for Unique<T> {
732 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
733 fmt::Pointer::fmt(&*self.pointer, f)
737 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
738 /// of this wrapper has shared ownership of the referent. Useful for
739 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
740 /// use raw pointers to manage the memory that they own.
741 #[allow(missing_debug_implementations)]
742 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
744 pub struct Shared<T: ?Sized> {
745 pointer: NonZero<*const T>,
746 // NOTE: this marker has no consequences for variance, but is necessary
747 // for dropck to understand that we logically own a `T`.
750 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
751 _marker: PhantomData<T>,
754 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
755 // NB: This impl is unnecessary, but should provide better error messages.
756 #[unstable(feature = "shared", issue = "27730")]
757 impl<T: ?Sized> !Send for Shared<T> { }
759 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
760 // NB: This impl is unnecessary, but should provide better error messages.
761 #[unstable(feature = "shared", issue = "27730")]
762 impl<T: ?Sized> !Sync for Shared<T> { }
764 #[unstable(feature = "shared", issue = "27730")]
765 impl<T: ?Sized> Shared<T> {
766 /// Creates a new `Shared`.
770 /// `ptr` must be non-null.
771 pub unsafe fn new(ptr: *mut T) -> Self {
772 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
776 #[unstable(feature = "shared", issue = "27730")]
777 impl<T: ?Sized> Clone for Shared<T> {
778 fn clone(&self) -> Self {
783 #[unstable(feature = "shared", issue = "27730")]
784 impl<T: ?Sized> Copy for Shared<T> { }
786 #[unstable(feature = "shared", issue = "27730")]
787 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
789 #[unstable(feature = "shared", issue = "27730")]
790 impl<T: ?Sized> Deref for Shared<T> {
791 type Target = *mut T;
794 fn deref(&self) -> &*mut T {
795 unsafe { mem::transmute(&*self.pointer) }
799 #[unstable(feature = "shared", issue = "27730")]
800 impl<T> fmt::Pointer for Shared<T> {
801 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
802 fmt::Pointer::fmt(&*self.pointer, f)