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](../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 #[unstable(feature = "drop_in_place", reason = "just exposed, needs FCP", issue = "27908")]
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 /// Variant of read_and_zero that writes the specific drop-flag byte
131 /// (which may be more appropriate than zero).
133 #[unstable(feature = "filling_drop",
134 reason = "may play a larger role in std::ptr future extensions",
136 pub unsafe fn read_and_drop<T>(dest: *mut T) -> T {
137 // Copy the data out from `dest`:
138 let tmp = read(&*dest);
140 // Now mark `dest` as dropped:
141 write_bytes(dest, mem::POST_DROP_U8, 1);
146 /// Overwrites a memory location with the given value without reading or
147 /// dropping the old value.
151 /// This operation is marked unsafe because it accepts a raw pointer.
153 /// It does not drop the contents of `dst`. This is safe, but it could leak
154 /// allocations or resources, so care must be taken not to overwrite an object
155 /// that should be dropped.
157 /// This is appropriate for initializing uninitialized memory, or overwriting
158 /// memory that has previously been `read` from.
160 #[stable(feature = "rust1", since = "1.0.0")]
161 pub unsafe fn write<T>(dst: *mut T, src: T) {
162 intrinsics::move_val_init(&mut *dst, src)
165 #[lang = "const_ptr"]
166 impl<T: ?Sized> *const T {
167 /// Returns true if the pointer is null.
168 #[stable(feature = "rust1", since = "1.0.0")]
170 pub fn is_null(self) -> bool where T: Sized {
174 /// Returns `None` if the pointer is null, or else returns a reference to
175 /// the value wrapped in `Some`.
179 /// While this method and its mutable counterpart are useful for
180 /// null-safety, it is important to note that this is still an unsafe
181 /// operation because the returned value could be pointing to invalid
183 #[unstable(feature = "ptr_as_ref",
184 reason = "Option is not clearly the right return type, and we \
185 may want to tie the return lifetime to a borrow of \
189 pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
197 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
198 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
202 /// Both the starting and resulting pointer must be either in bounds or one
203 /// byte past the end of an allocated object. If either pointer is out of
204 /// bounds or arithmetic overflow occurs then
205 /// any further use of the returned value will result in undefined behavior.
206 #[stable(feature = "rust1", since = "1.0.0")]
208 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
209 intrinsics::offset(self, count)
214 impl<T: ?Sized> *mut T {
215 /// Returns true if the pointer is null.
216 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn is_null(self) -> bool where T: Sized {
222 /// Returns `None` if the pointer is null, or else returns a reference to
223 /// the value wrapped in `Some`.
227 /// While this method and its mutable counterpart are useful for
228 /// null-safety, it is important to note that this is still an unsafe
229 /// operation because the returned value could be pointing to invalid
231 #[unstable(feature = "ptr_as_ref",
232 reason = "Option is not clearly the right return type, and we \
233 may want to tie the return lifetime to a borrow of \
237 pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
245 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
246 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
250 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
251 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
252 /// the pointer is used.
253 #[stable(feature = "rust1", since = "1.0.0")]
255 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
256 intrinsics::offset(self, count) as *mut T
259 /// Returns `None` if the pointer is null, or else returns a mutable
260 /// reference to the value wrapped in `Some`.
264 /// As with `as_ref`, this is unsafe because it cannot verify the validity
265 /// of the returned pointer.
266 #[unstable(feature = "ptr_as_ref",
267 reason = "return value does not necessarily convey all possible \
271 pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> where T: Sized {
280 // Equality for pointers
281 #[stable(feature = "rust1", since = "1.0.0")]
282 impl<T: ?Sized> PartialEq for *const T {
284 fn eq(&self, other: &*const T) -> bool { *self == *other }
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<T: ?Sized> Eq for *const T {}
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<T: ?Sized> PartialEq for *mut T {
293 fn eq(&self, other: &*mut T) -> bool { *self == *other }
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<T: ?Sized> Eq for *mut T {}
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl<T: ?Sized> Clone for *const T {
302 fn clone(&self) -> *const T {
307 #[stable(feature = "rust1", since = "1.0.0")]
308 impl<T: ?Sized> Clone for *mut T {
310 fn clone(&self) -> *mut T {
315 // Impls for function pointers
316 macro_rules! fnptr_impls_safety_abi {
317 ($FnTy: ty, $($Arg: ident),*) => {
318 #[stable(feature = "rust1", since = "1.0.0")]
319 impl<Ret, $($Arg),*> Clone for $FnTy {
321 fn clone(&self) -> Self {
326 #[stable(feature = "fnptr_impls", since = "1.4.0")]
327 impl<Ret, $($Arg),*> PartialEq for $FnTy {
329 fn eq(&self, other: &Self) -> bool {
330 *self as usize == *other as usize
334 #[stable(feature = "fnptr_impls", since = "1.4.0")]
335 impl<Ret, $($Arg),*> Eq for $FnTy {}
337 #[stable(feature = "fnptr_impls", since = "1.4.0")]
338 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
340 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
341 (*self as usize).partial_cmp(&(*other as usize))
345 #[stable(feature = "fnptr_impls", since = "1.4.0")]
346 impl<Ret, $($Arg),*> Ord for $FnTy {
348 fn cmp(&self, other: &Self) -> Ordering {
349 (*self as usize).cmp(&(*other as usize))
353 #[stable(feature = "fnptr_impls", since = "1.4.0")]
354 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
355 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
356 state.write_usize(*self as usize)
360 #[stable(feature = "fnptr_impls", since = "1.4.0")]
361 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
362 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
363 fmt::Pointer::fmt(&(*self as *const ()), f)
367 #[stable(feature = "fnptr_impls", since = "1.4.0")]
368 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
369 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
370 fmt::Pointer::fmt(&(*self as *const ()), f)
376 macro_rules! fnptr_impls_args {
377 ($($Arg: ident),*) => {
378 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
379 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
380 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
381 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
385 fnptr_impls_args! { }
386 fnptr_impls_args! { A }
387 fnptr_impls_args! { A, B }
388 fnptr_impls_args! { A, B, C }
389 fnptr_impls_args! { A, B, C, D }
390 fnptr_impls_args! { A, B, C, D, E }
391 fnptr_impls_args! { A, B, C, D, E, F }
392 fnptr_impls_args! { A, B, C, D, E, F, G }
393 fnptr_impls_args! { A, B, C, D, E, F, G, H }
394 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
395 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
396 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
397 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
399 // Comparison for pointers
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl<T: ?Sized> Ord for *const T {
403 fn cmp(&self, other: &*const T) -> Ordering {
406 } else if self == other {
414 #[stable(feature = "rust1", since = "1.0.0")]
415 impl<T: ?Sized> PartialOrd for *const T {
417 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
418 Some(self.cmp(other))
422 fn lt(&self, other: &*const T) -> bool { *self < *other }
425 fn le(&self, other: &*const T) -> bool { *self <= *other }
428 fn gt(&self, other: &*const T) -> bool { *self > *other }
431 fn ge(&self, other: &*const T) -> bool { *self >= *other }
434 #[stable(feature = "rust1", since = "1.0.0")]
435 impl<T: ?Sized> Ord for *mut T {
437 fn cmp(&self, other: &*mut T) -> Ordering {
440 } else if self == other {
448 #[stable(feature = "rust1", since = "1.0.0")]
449 impl<T: ?Sized> PartialOrd for *mut T {
451 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
452 Some(self.cmp(other))
456 fn lt(&self, other: &*mut T) -> bool { *self < *other }
459 fn le(&self, other: &*mut T) -> bool { *self <= *other }
462 fn gt(&self, other: &*mut T) -> bool { *self > *other }
465 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
468 /// A wrapper around a raw `*mut T` that indicates that the possessor
469 /// of this wrapper owns the referent. This in turn implies that the
470 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
471 /// `*mut T` (which conveys no particular ownership semantics). It
472 /// also implies that the referent of the pointer should not be
473 /// modified without a unique path to the `Unique` reference. Useful
474 /// for building abstractions like `Vec<T>` or `Box<T>`, which
475 /// internally use raw pointers to manage the memory that they own.
476 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
478 pub struct Unique<T: ?Sized> {
479 pointer: NonZero<*const T>,
480 // NOTE: this marker has no consequences for variance, but is necessary
481 // for dropck to understand that we logically own a `T`.
484 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
485 _marker: PhantomData<T>,
488 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
489 /// reference is unaliased. Note that this aliasing invariant is
490 /// unenforced by the type system; the abstraction using the
491 /// `Unique` must enforce it.
492 #[unstable(feature = "unique", issue = "27730")]
493 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
495 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
496 /// reference is unaliased. Note that this aliasing invariant is
497 /// unenforced by the type system; the abstraction using the
498 /// `Unique` must enforce it.
499 #[unstable(feature = "unique", issue = "27730")]
500 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
502 #[unstable(feature = "unique", issue = "27730")]
503 impl<T: ?Sized> Unique<T> {
504 /// Creates a new `Unique`.
505 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
506 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
509 /// Dereferences the content.
510 pub unsafe fn get(&self) -> &T {
514 /// Mutably dereferences the content.
515 pub unsafe fn get_mut(&mut self) -> &mut T {
520 #[unstable(feature = "unique", issue = "27730")]
521 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
523 #[unstable(feature = "unique", issue= "27730")]
524 impl<T:?Sized> Deref for Unique<T> {
525 type Target = *mut T;
528 fn deref(&self) -> &*mut T {
529 unsafe { mem::transmute(&*self.pointer) }
533 #[stable(feature = "rust1", since = "1.0.0")]
534 impl<T> fmt::Pointer for Unique<T> {
535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
536 fmt::Pointer::fmt(&*self.pointer, f)
540 /// A wrapper around a raw `*mut T` that indicates that the possessor
541 /// of this wrapper has shared ownership of the referent. Useful for
542 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
543 /// use raw pointers to manage the memory that they own.
544 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
546 pub struct Shared<T: ?Sized> {
547 pointer: NonZero<*const T>,
548 // NOTE: this marker has no consequences for variance, but is necessary
549 // for dropck to understand that we logically own a `T`.
552 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
553 _marker: PhantomData<T>,
556 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
557 // NB: This impl is unnecessary, but should provide better error messages.
558 #[unstable(feature = "shared", issue = "27730")]
559 impl<T: ?Sized> !Send for Shared<T> { }
561 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
562 // NB: This impl is unnecessary, but should provide better error messages.
563 #[unstable(feature = "shared", issue = "27730")]
564 impl<T: ?Sized> !Sync for Shared<T> { }
566 #[unstable(feature = "shared", issue = "27730")]
567 impl<T: ?Sized> Shared<T> {
568 /// Creates a new `Shared`.
569 pub unsafe fn new(ptr: *mut T) -> Self {
570 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
574 #[unstable(feature = "shared", issue = "27730")]
575 impl<T: ?Sized> Clone for Shared<T> {
576 fn clone(&self) -> Self {
581 #[unstable(feature = "shared", issue = "27730")]
582 impl<T: ?Sized> Copy for Shared<T> { }
584 #[unstable(feature = "shared", issue = "27730")]
585 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
587 #[unstable(feature = "shared", issue = "27730")]
588 impl<T: ?Sized> Deref for Shared<T> {
589 type Target = *mut T;
592 fn deref(&self) -> &*mut T {
593 unsafe { mem::transmute(&*self.pointer) }
597 #[unstable(feature = "shared", issue = "27730")]
598 impl<T> fmt::Pointer for Shared<T> {
599 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
600 fmt::Pointer::fmt(&*self.pointer, f)