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`.
123 #[stable(feature = "rust1", since = "1.0.0")]
124 pub unsafe fn read
<T
>(src
: *const T
) -> T
{
125 let mut tmp
: T
= mem
::uninitialized();
126 copy_nonoverlapping(src
, &mut tmp
, 1);
130 #[allow(missing_docs)]
132 #[unstable(feature = "filling_drop",
133 reason
= "may play a larger role in std::ptr future extensions",
135 pub unsafe fn read_and_drop
<T
>(dest
: *mut T
) -> T
{
136 // Copy the data out from `dest`:
137 let tmp
= read(&*dest
);
139 // Now mark `dest` as dropped:
140 write_bytes(dest
, mem
::POST_DROP_U8
, 1);
145 /// Overwrites a memory location with the given value without reading or
146 /// dropping the old value.
150 /// This operation is marked unsafe because it accepts a raw pointer.
152 /// It does not drop the contents of `dst`. This is safe, but it could leak
153 /// allocations or resources, so care must be taken not to overwrite an object
154 /// that should be dropped.
156 /// This is appropriate for initializing uninitialized memory, or overwriting
157 /// memory that has previously been `read` from.
159 #[stable(feature = "rust1", since = "1.0.0")]
160 pub unsafe fn write
<T
>(dst
: *mut T
, src
: T
) {
161 intrinsics
::move_val_init(&mut *dst
, src
)
164 /// Performs a volatile read of the value from `src` without moving it. This
165 /// leaves the memory in `src` unchanged.
167 /// Volatile operations are intended to act on I/O memory, and are guaranteed
168 /// to not be elided or reordered by the compiler across other volatile
173 /// Rust does not currently have a rigorously and formally defined memory model,
174 /// so the precise semantics of what "volatile" means here is subject to change
175 /// over time. That being said, the semantics will almost always end up pretty
176 /// similar to [C11's definition of volatile][c11].
178 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
182 /// Beyond accepting a raw pointer, this is unsafe because it semantically
183 /// moves the value out of `src` without preventing further usage of `src`.
184 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
185 /// `src` is not used before the data is overwritten again (e.g. with `write`,
186 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
187 /// because it will attempt to drop the value previously at `*src`.
189 #[stable(feature = "volatile", since = "1.9.0")]
190 pub unsafe fn read_volatile
<T
>(src
: *const T
) -> T
{
191 intrinsics
::volatile_load(src
)
194 /// Performs a volatile write of a memory location with the given value without
195 /// reading or dropping the old value.
197 /// Volatile operations are intended to act on I/O memory, and are guaranteed
198 /// to not be elided or reordered by the compiler across other volatile
203 /// Rust does not currently have a rigorously and formally defined memory model,
204 /// so the precise semantics of what "volatile" means here is subject to change
205 /// over time. That being said, the semantics will almost always end up pretty
206 /// similar to [C11's definition of volatile][c11].
208 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
212 /// This operation is marked unsafe because it accepts a raw pointer.
214 /// It does not drop the contents of `dst`. This is safe, but it could leak
215 /// allocations or resources, so care must be taken not to overwrite an object
216 /// that should be dropped.
218 /// This is appropriate for initializing uninitialized memory, or overwriting
219 /// memory that has previously been `read` from.
221 #[stable(feature = "volatile", since = "1.9.0")]
222 pub unsafe fn write_volatile
<T
>(dst
: *mut T
, src
: T
) {
223 intrinsics
::volatile_store(dst
, src
);
226 #[lang = "const_ptr"]
227 impl<T
: ?Sized
> *const T
{
228 /// Returns true if the pointer is null.
235 /// let s: &str = "Follow the rabbit";
236 /// let ptr: *const u8 = s.as_ptr();
237 /// assert!(!ptr.is_null());
239 #[stable(feature = "rust1", since = "1.0.0")]
241 pub fn is_null(self) -> bool
where T
: Sized
{
245 /// Returns `None` if the pointer is null, or else returns a reference to
246 /// the value wrapped in `Some`.
250 /// While this method and its mutable counterpart are useful for
251 /// null-safety, it is important to note that this is still an unsafe
252 /// operation because the returned value could be pointing to invalid
255 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
256 /// not necessarily reflect the actual lifetime of the data.
263 /// let val: *const u8 = &10u8 as *const u8;
266 /// if let Some(val_back) = val.as_ref() {
267 /// println!("We got back the value: {}!", val_back);
271 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
273 pub unsafe fn as_ref
<'a
>(self) -> Option
<&'a T
> where T
: Sized
{
281 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
282 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
286 /// Both the starting and resulting pointer must be either in bounds or one
287 /// byte past the end of an allocated object. If either pointer is out of
288 /// bounds or arithmetic overflow occurs then
289 /// any further use of the returned value will result in undefined behavior.
296 /// let s: &str = "123";
297 /// let ptr: *const u8 = s.as_ptr();
300 /// println!("{}", *ptr.offset(1) as char);
301 /// println!("{}", *ptr.offset(2) as char);
304 #[stable(feature = "rust1", since = "1.0.0")]
306 pub unsafe fn offset(self, count
: isize) -> *const T
where T
: Sized
{
307 intrinsics
::offset(self, count
)
312 impl<T
: ?Sized
> *mut T
{
313 /// Returns true if the pointer is null.
320 /// let mut s = [1, 2, 3];
321 /// let ptr: *mut u32 = s.as_mut_ptr();
322 /// assert!(!ptr.is_null());
324 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn is_null(self) -> bool
where T
: Sized
{
330 /// Returns `None` if the pointer is null, or else returns a reference to
331 /// the value wrapped in `Some`.
335 /// While this method and its mutable counterpart are useful for
336 /// null-safety, it is important to note that this is still an unsafe
337 /// operation because the returned value could be pointing to invalid
340 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
341 /// not necessarily reflect the actual lifetime of the data.
348 /// let val: *mut u8 = &mut 10u8 as *mut u8;
351 /// if let Some(val_back) = val.as_ref() {
352 /// println!("We got back the value: {}!", val_back);
356 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
358 pub unsafe fn as_ref
<'a
>(self) -> Option
<&'a T
> where T
: Sized
{
366 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
367 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
371 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
372 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
373 /// the pointer is used.
380 /// let mut s = [1, 2, 3];
381 /// let ptr: *mut u32 = s.as_mut_ptr();
384 /// println!("{}", *ptr.offset(1));
385 /// println!("{}", *ptr.offset(2));
388 #[stable(feature = "rust1", since = "1.0.0")]
390 pub unsafe fn offset(self, count
: isize) -> *mut T
where T
: Sized
{
391 intrinsics
::offset(self, count
) as *mut T
394 /// Returns `None` if the pointer is null, or else returns a mutable
395 /// reference to the value wrapped in `Some`.
399 /// As with `as_ref`, this is unsafe because it cannot verify the validity
400 /// of the returned pointer, nor can it ensure that the lifetime `'a`
401 /// returned is indeed a valid lifetime for the contained data.
408 /// let mut s = [1, 2, 3];
409 /// let ptr: *mut u32 = s.as_mut_ptr();
411 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
413 pub unsafe fn as_mut
<'a
>(self) -> Option
<&'a
mut T
> where T
: Sized
{
422 // Equality for pointers
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl<T
: ?Sized
> PartialEq
for *const T
{
426 fn eq(&self, other
: &*const T
) -> bool { *self == *other }
429 #[stable(feature = "rust1", since = "1.0.0")]
430 impl<T
: ?Sized
> Eq
for *const T {}
432 #[stable(feature = "rust1", since = "1.0.0")]
433 impl<T
: ?Sized
> PartialEq
for *mut T
{
435 fn eq(&self, other
: &*mut T
) -> bool { *self == *other }
438 #[stable(feature = "rust1", since = "1.0.0")]
439 impl<T
: ?Sized
> Eq
for *mut T {}
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl<T
: ?Sized
> Clone
for *const T
{
444 fn clone(&self) -> *const T
{
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl<T
: ?Sized
> Clone
for *mut T
{
452 fn clone(&self) -> *mut T
{
457 // Impls for function pointers
458 macro_rules
! fnptr_impls_safety_abi
{
459 ($FnTy
: ty
, $
($Arg
: ident
),*) => {
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl<Ret
, $
($Arg
),*> Clone
for $FnTy
{
463 fn clone(&self) -> Self {
468 #[stable(feature = "fnptr_impls", since = "1.4.0")]
469 impl<Ret
, $
($Arg
),*> PartialEq
for $FnTy
{
471 fn eq(&self, other
: &Self) -> bool
{
472 *self as usize == *other
as usize
476 #[stable(feature = "fnptr_impls", since = "1.4.0")]
477 impl<Ret
, $
($Arg
),*> Eq
for $FnTy {}
479 #[stable(feature = "fnptr_impls", since = "1.4.0")]
480 impl<Ret
, $
($Arg
),*> PartialOrd
for $FnTy
{
482 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
483 (*self as usize).partial_cmp(&(*other
as usize))
487 #[stable(feature = "fnptr_impls", since = "1.4.0")]
488 impl<Ret
, $
($Arg
),*> Ord
for $FnTy
{
490 fn cmp(&self, other
: &Self) -> Ordering
{
491 (*self as usize).cmp(&(*other
as usize))
495 #[stable(feature = "fnptr_impls", since = "1.4.0")]
496 impl<Ret
, $
($Arg
),*> hash
::Hash
for $FnTy
{
497 fn hash
<HH
: hash
::Hasher
>(&self, state
: &mut HH
) {
498 state
.write_usize(*self as usize)
502 #[stable(feature = "fnptr_impls", since = "1.4.0")]
503 impl<Ret
, $
($Arg
),*> fmt
::Pointer
for $FnTy
{
504 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
505 fmt
::Pointer
::fmt(&(*self as *const ()), f
)
509 #[stable(feature = "fnptr_impls", since = "1.4.0")]
510 impl<Ret
, $
($Arg
),*> fmt
::Debug
for $FnTy
{
511 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
512 fmt
::Pointer
::fmt(&(*self as *const ()), f
)
518 macro_rules
! fnptr_impls_args
{
519 ($
($Arg
: ident
),*) => {
520 fnptr_impls_safety_abi
! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
521 fnptr_impls_safety_abi
! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
522 fnptr_impls_safety_abi
! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
523 fnptr_impls_safety_abi
! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
527 fnptr_impls_args
! { }
528 fnptr_impls_args
! { A }
529 fnptr_impls_args
! { A, B }
530 fnptr_impls_args
! { A, B, C }
531 fnptr_impls_args
! { A, B, C, D }
532 fnptr_impls_args
! { A, B, C, D, E }
533 fnptr_impls_args
! { A, B, C, D, E, F }
534 fnptr_impls_args
! { A, B, C, D, E, F, G }
535 fnptr_impls_args
! { A, B, C, D, E, F, G, H }
536 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I }
537 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I, J }
538 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I, J, K }
539 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I, J, K, L }
541 // Comparison for pointers
542 #[stable(feature = "rust1", since = "1.0.0")]
543 impl<T
: ?Sized
> Ord
for *const T
{
545 fn cmp(&self, other
: &*const T
) -> Ordering
{
548 } else if self == other
{
556 #[stable(feature = "rust1", since = "1.0.0")]
557 impl<T
: ?Sized
> PartialOrd
for *const T
{
559 fn partial_cmp(&self, other
: &*const T
) -> Option
<Ordering
> {
560 Some(self.cmp(other
))
564 fn lt(&self, other
: &*const T
) -> bool { *self < *other }
567 fn le(&self, other
: &*const T
) -> bool { *self <= *other }
570 fn gt(&self, other
: &*const T
) -> bool { *self > *other }
573 fn ge(&self, other
: &*const T
) -> bool { *self >= *other }
576 #[stable(feature = "rust1", since = "1.0.0")]
577 impl<T
: ?Sized
> Ord
for *mut T
{
579 fn cmp(&self, other
: &*mut T
) -> Ordering
{
582 } else if self == other
{
590 #[stable(feature = "rust1", since = "1.0.0")]
591 impl<T
: ?Sized
> PartialOrd
for *mut T
{
593 fn partial_cmp(&self, other
: &*mut T
) -> Option
<Ordering
> {
594 Some(self.cmp(other
))
598 fn lt(&self, other
: &*mut T
) -> bool { *self < *other }
601 fn le(&self, other
: &*mut T
) -> bool { *self <= *other }
604 fn gt(&self, other
: &*mut T
) -> bool { *self > *other }
607 fn ge(&self, other
: &*mut T
) -> bool { *self >= *other }
610 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
611 /// of this wrapper owns the referent. This in turn implies that the
612 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
613 /// `*mut T` (which conveys no particular ownership semantics). It
614 /// also implies that the referent of the pointer should not be
615 /// modified without a unique path to the `Unique` reference. Useful
616 /// for building abstractions like `Vec<T>` or `Box<T>`, which
617 /// internally use raw pointers to manage the memory that they own.
618 #[allow(missing_debug_implementations)]
619 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
621 pub struct Unique
<T
: ?Sized
> {
622 pointer
: NonZero
<*const T
>,
623 // NOTE: this marker has no consequences for variance, but is necessary
624 // for dropck to understand that we logically own a `T`.
627 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
628 _marker
: PhantomData
<T
>,
631 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
632 /// reference is unaliased. Note that this aliasing invariant is
633 /// unenforced by the type system; the abstraction using the
634 /// `Unique` must enforce it.
635 #[unstable(feature = "unique", issue = "27730")]
636 unsafe impl<T
: Send
+ ?Sized
> Send
for Unique
<T
> { }
638 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
639 /// reference is unaliased. Note that this aliasing invariant is
640 /// unenforced by the type system; the abstraction using the
641 /// `Unique` must enforce it.
642 #[unstable(feature = "unique", issue = "27730")]
643 unsafe impl<T
: Sync
+ ?Sized
> Sync
for Unique
<T
> { }
645 #[unstable(feature = "unique", issue = "27730")]
646 impl<T
: ?Sized
> Unique
<T
> {
647 /// Creates a new `Unique`.
651 /// `ptr` must be non-null.
652 pub const unsafe fn new(ptr
: *mut T
) -> Unique
<T
> {
653 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
656 /// Dereferences the content.
657 pub unsafe fn get(&self) -> &T
{
661 /// Mutably dereferences the content.
662 pub unsafe fn get_mut(&mut self) -> &mut T
{
667 #[unstable(feature = "unique", issue = "27730")]
668 impl<T
: ?Sized
, U
: ?Sized
> CoerceUnsized
<Unique
<U
>> for Unique
<T
> where T
: Unsize
<U
> { }
670 #[unstable(feature = "unique", issue= "27730")]
671 impl<T
:?Sized
> Deref
for Unique
<T
> {
672 type Target
= *mut T
;
675 fn deref(&self) -> &*mut T
{
676 unsafe { mem::transmute(&*self.pointer) }
680 #[stable(feature = "rust1", since = "1.0.0")]
681 impl<T
> fmt
::Pointer
for Unique
<T
> {
682 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
683 fmt
::Pointer
::fmt(&*self.pointer
, f
)
687 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
688 /// of this wrapper has shared ownership of the referent. Useful for
689 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
690 /// use raw pointers to manage the memory that they own.
691 #[allow(missing_debug_implementations)]
692 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
694 pub struct Shared
<T
: ?Sized
> {
695 pointer
: NonZero
<*const T
>,
696 // NOTE: this marker has no consequences for variance, but is necessary
697 // for dropck to understand that we logically own a `T`.
700 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
701 _marker
: PhantomData
<T
>,
704 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
705 // NB: This impl is unnecessary, but should provide better error messages.
706 #[unstable(feature = "shared", issue = "27730")]
707 impl<T
: ?Sized
> !Send
for Shared
<T
> { }
709 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
710 // NB: This impl is unnecessary, but should provide better error messages.
711 #[unstable(feature = "shared", issue = "27730")]
712 impl<T
: ?Sized
> !Sync
for Shared
<T
> { }
714 #[unstable(feature = "shared", issue = "27730")]
715 impl<T
: ?Sized
> Shared
<T
> {
716 /// Creates a new `Shared`.
720 /// `ptr` must be non-null.
721 pub unsafe fn new(ptr
: *mut T
) -> Self {
722 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
726 #[unstable(feature = "shared", issue = "27730")]
727 impl<T
: ?Sized
> Clone
for Shared
<T
> {
728 fn clone(&self) -> Self {
733 #[unstable(feature = "shared", issue = "27730")]
734 impl<T
: ?Sized
> Copy
for Shared
<T
> { }
736 #[unstable(feature = "shared", issue = "27730")]
737 impl<T
: ?Sized
, U
: ?Sized
> CoerceUnsized
<Shared
<U
>> for Shared
<T
> where T
: Unsize
<U
> { }
739 #[unstable(feature = "shared", issue = "27730")]
740 impl<T
: ?Sized
> Deref
for Shared
<T
> {
741 type Target
= *mut T
;
744 fn deref(&self) -> &*mut T
{
745 unsafe { mem::transmute(&*self.pointer) }
749 #[unstable(feature = "shared", issue = "27730")]
750 impl<T
> fmt
::Pointer
for Shared
<T
> {
751 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
752 fmt
::Pointer
::fmt(&*self.pointer
, f
)