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 pub use intrinsics::drop_in_place;
45 /// Creates a null raw pointer.
52 /// let p: *const i32 = ptr::null();
53 /// assert!(p.is_null());
56 #[stable(feature = "rust1", since = "1.0.0")]
57 pub const fn null<T>() -> *const T { 0 as *const T }
59 /// Creates a null mutable raw pointer.
66 /// let p: *mut i32 = ptr::null_mut();
67 /// assert!(p.is_null());
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
73 /// Swaps the values at two mutable locations of the same type, without
74 /// deinitializing either. They may overlap, unlike `mem::swap` which is
75 /// otherwise equivalent.
79 /// This is only unsafe because it accepts a raw pointer.
81 #[stable(feature = "rust1", since = "1.0.0")]
82 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
83 // Give ourselves some scratch space to work with
84 let mut tmp: T = mem::uninitialized();
87 copy_nonoverlapping(x, &mut tmp, 1);
88 copy(y, x, 1); // `x` and `y` may overlap
89 copy_nonoverlapping(&tmp, y, 1);
91 // y and t now point to the same thing, but we need to completely forget `tmp`
92 // because it's no longer relevant.
96 /// Replaces the value at `dest` with `src`, returning the old
97 /// value, without dropping either.
101 /// This is only unsafe because it accepts a raw pointer.
102 /// Otherwise, this operation is identical to `mem::replace`.
104 #[stable(feature = "rust1", since = "1.0.0")]
105 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
106 mem::swap(&mut *dest, &mut src); // cannot overlap
110 /// Reads the value from `src` without moving it. This leaves the
111 /// memory in `src` unchanged.
115 /// Beyond accepting a raw pointer, this is unsafe because it semantically
116 /// moves the value out of `src` without preventing further usage of `src`.
117 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
118 /// `src` is not used before the data is overwritten again (e.g. with `write`,
119 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
120 /// because it will attempt to drop the value previously at `*src`.
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub unsafe fn read<T>(src: *const T) -> T {
124 let mut tmp: T = mem::uninitialized();
125 copy_nonoverlapping(src, &mut tmp, 1);
129 /// Variant of read_and_zero that writes the specific drop-flag byte
130 /// (which may be more appropriate than zero).
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 #[stable(feature = "rust1", since = "1.0.0")]
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)
213 #[stable(feature = "rust1", since = "1.0.0")]
215 impl<T: ?Sized> *mut T {
216 /// Returns true if the pointer is null.
217 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn is_null(self) -> bool where T: Sized {
223 /// Returns `None` if the pointer is null, or else returns a reference to
224 /// the value wrapped in `Some`.
228 /// While this method and its mutable counterpart are useful for
229 /// null-safety, it is important to note that this is still an unsafe
230 /// operation because the returned value could be pointing to invalid
232 #[unstable(feature = "ptr_as_ref",
233 reason = "Option is not clearly the right return type, and we \
234 may want to tie the return lifetime to a borrow of \
238 pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
246 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
247 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
251 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
252 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
253 /// the pointer is used.
254 #[stable(feature = "rust1", since = "1.0.0")]
256 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
257 intrinsics::offset(self, count) as *mut T
260 /// Returns `None` if the pointer is null, or else returns a mutable
261 /// reference to the value wrapped in `Some`.
265 /// As with `as_ref`, this is unsafe because it cannot verify the validity
266 /// of the returned pointer.
267 #[unstable(feature = "ptr_as_ref",
268 reason = "return value does not necessarily convey all possible \
272 pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> where T: Sized {
281 // Equality for pointers
282 #[stable(feature = "rust1", since = "1.0.0")]
283 impl<T: ?Sized> PartialEq for *const T {
285 fn eq(&self, other: &*const T) -> bool { *self == *other }
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl<T: ?Sized> Eq for *const T {}
291 #[stable(feature = "rust1", since = "1.0.0")]
292 impl<T: ?Sized> PartialEq for *mut T {
294 fn eq(&self, other: &*mut T) -> bool { *self == *other }
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl<T: ?Sized> Eq for *mut T {}
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl<T: ?Sized> Clone for *const T {
303 fn clone(&self) -> *const T {
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<T: ?Sized> Clone for *mut T {
311 fn clone(&self) -> *mut T {
316 // Impls for function pointers
317 macro_rules! fnptr_impls_safety_abi {
318 ($FnTy: ty, $($Arg: ident),*) => {
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl<Ret, $($Arg),*> Clone for $FnTy {
322 fn clone(&self) -> Self {
327 #[stable(feature = "fnptr_impls", since = "1.4.0")]
328 impl<Ret, $($Arg),*> PartialEq for $FnTy {
330 fn eq(&self, other: &Self) -> bool {
331 *self as usize == *other as usize
335 #[stable(feature = "fnptr_impls", since = "1.4.0")]
336 impl<Ret, $($Arg),*> Eq for $FnTy {}
338 #[stable(feature = "fnptr_impls", since = "1.4.0")]
339 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
341 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
342 (*self as usize).partial_cmp(&(*other as usize))
346 #[stable(feature = "fnptr_impls", since = "1.4.0")]
347 impl<Ret, $($Arg),*> Ord for $FnTy {
349 fn cmp(&self, other: &Self) -> Ordering {
350 (*self as usize).cmp(&(*other as usize))
354 #[stable(feature = "fnptr_impls", since = "1.4.0")]
355 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
356 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
357 state.write_usize(*self as usize)
361 #[stable(feature = "fnptr_impls", since = "1.4.0")]
362 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
363 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
364 fmt::Pointer::fmt(&(*self as *const ()), f)
368 #[stable(feature = "fnptr_impls", since = "1.4.0")]
369 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
370 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
371 fmt::Pointer::fmt(&(*self as *const ()), f)
377 macro_rules! fnptr_impls_args {
378 ($($Arg: ident),*) => {
379 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
380 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
381 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
382 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
386 fnptr_impls_args! { }
387 fnptr_impls_args! { A }
388 fnptr_impls_args! { A, B }
389 fnptr_impls_args! { A, B, C }
390 fnptr_impls_args! { A, B, C, D }
391 fnptr_impls_args! { A, B, C, D, E }
392 fnptr_impls_args! { A, B, C, D, E, F }
393 fnptr_impls_args! { A, B, C, D, E, F, G }
394 fnptr_impls_args! { A, B, C, D, E, F, G, H }
395 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
396 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
397 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
398 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
400 // Comparison for pointers
401 #[stable(feature = "rust1", since = "1.0.0")]
402 impl<T: ?Sized> Ord for *const T {
404 fn cmp(&self, other: &*const T) -> Ordering {
407 } else if self == other {
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl<T: ?Sized> PartialOrd for *const T {
418 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
419 Some(self.cmp(other))
423 fn lt(&self, other: &*const T) -> bool { *self < *other }
426 fn le(&self, other: &*const T) -> bool { *self <= *other }
429 fn gt(&self, other: &*const T) -> bool { *self > *other }
432 fn ge(&self, other: &*const T) -> bool { *self >= *other }
435 #[stable(feature = "rust1", since = "1.0.0")]
436 impl<T: ?Sized> Ord for *mut T {
438 fn cmp(&self, other: &*mut T) -> Ordering {
441 } else if self == other {
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl<T: ?Sized> PartialOrd for *mut T {
452 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
453 Some(self.cmp(other))
457 fn lt(&self, other: &*mut T) -> bool { *self < *other }
460 fn le(&self, other: &*mut T) -> bool { *self <= *other }
463 fn gt(&self, other: &*mut T) -> bool { *self > *other }
466 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
469 /// A wrapper around a raw `*mut T` that indicates that the possessor
470 /// of this wrapper owns the referent. This in turn implies that the
471 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
472 /// `*mut T` (which conveys no particular ownership semantics). It
473 /// also implies that the referent of the pointer should not be
474 /// modified without a unique path to the `Unique` reference. Useful
475 /// for building abstractions like `Vec<T>` or `Box<T>`, which
476 /// internally use raw pointers to manage the memory that they own.
477 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
479 pub struct Unique<T: ?Sized> {
480 pointer: NonZero<*const T>,
481 // NOTE: this marker has no consequences for variance, but is necessary
482 // for dropck to understand that we logically own a `T`.
485 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
486 _marker: PhantomData<T>,
489 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
490 /// reference is unaliased. Note that this aliasing invariant is
491 /// unenforced by the type system; the abstraction using the
492 /// `Unique` must enforce it.
493 #[unstable(feature = "unique", issue = "27730")]
494 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
496 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
497 /// reference is unaliased. Note that this aliasing invariant is
498 /// unenforced by the type system; the abstraction using the
499 /// `Unique` must enforce it.
500 #[unstable(feature = "unique", issue = "27730")]
501 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
504 macro_rules! unique_new {
506 /// Creates a new `Unique`.
507 pub unsafe fn new(ptr: *mut T) -> Unique<T> {
508 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
513 macro_rules! unique_new {
515 /// Creates a new `Unique`.
516 pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
517 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
522 #[unstable(feature = "unique", issue = "27730")]
523 impl<T: ?Sized> Unique<T> {
526 /// Dereferences the content.
527 pub unsafe fn get(&self) -> &T {
531 /// Mutably dereferences the content.
532 pub unsafe fn get_mut(&mut self) -> &mut T {
537 #[cfg(not(stage0))] // remove cfg after new snapshot
538 #[unstable(feature = "unique", issue = "27730")]
539 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
541 #[unstable(feature = "unique", issue= "27730")]
542 impl<T:?Sized> Deref for Unique<T> {
543 type Target = *mut T;
546 fn deref(&self) -> &*mut T {
547 unsafe { mem::transmute(&*self.pointer) }
551 #[stable(feature = "rust1", since = "1.0.0")]
552 impl<T> fmt::Pointer for Unique<T> {
553 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
554 fmt::Pointer::fmt(&*self.pointer, f)
558 /// A wrapper around a raw `*mut T` that indicates that the possessor
559 /// of this wrapper has shared ownership of the referent. Useful for
560 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
561 /// use raw pointers to manage the memory that they own.
562 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
564 pub struct Shared<T: ?Sized> {
565 pointer: NonZero<*const T>,
566 // NOTE: this marker has no consequences for variance, but is necessary
567 // for dropck to understand that we logically own a `T`.
570 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
571 _marker: PhantomData<T>,
574 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
575 // NB: This impl is unnecessary, but should provide better error messages.
576 #[unstable(feature = "shared", issue = "27730")]
577 impl<T: ?Sized> !Send for Shared<T> { }
579 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
580 // NB: This impl is unnecessary, but should provide better error messages.
581 #[unstable(feature = "shared", issue = "27730")]
582 impl<T: ?Sized> !Sync for Shared<T> { }
584 #[unstable(feature = "shared", issue = "27730")]
585 impl<T: ?Sized> Shared<T> {
586 /// Creates a new `Shared`.
587 pub unsafe fn new(ptr: *mut T) -> Self {
588 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
592 #[unstable(feature = "shared", issue = "27730")]
593 impl<T: ?Sized> Clone for Shared<T> {
594 fn clone(&self) -> Self {
599 #[unstable(feature = "shared", issue = "27730")]
600 impl<T: ?Sized> Copy for Shared<T> { }
602 #[cfg(not(stage0))] // remove cfg after new snapshot
603 #[unstable(feature = "shared", issue = "27730")]
604 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
606 #[unstable(feature = "shared", issue = "27730")]
607 impl<T: ?Sized> Deref for Shared<T> {
608 type Target = *mut T;
611 fn deref(&self) -> &*mut T {
612 unsafe { mem::transmute(&*self.pointer) }
616 #[unstable(feature = "shared", issue = "27730")]
617 impl<T> fmt::Pointer for Shared<T> {
618 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
619 fmt::Pointer::fmt(&*self.pointer, f)