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 /// 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`.
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub unsafe fn read<T>(src: *const T) -> T {
122 let mut tmp: T = mem::uninitialized();
123 copy_nonoverlapping(src, &mut tmp, 1);
127 /// Variant of read_and_zero that writes the specific drop-flag byte
128 /// (which may be more appropriate than zero).
130 #[unstable(feature = "filling_drop",
131 reason = "may play a larger role in std::ptr future extensions",
133 pub unsafe fn read_and_drop<T>(dest: *mut T) -> T {
134 // Copy the data out from `dest`:
135 let tmp = read(&*dest);
137 // Now mark `dest` as dropped:
138 write_bytes(dest, mem::POST_DROP_U8, 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.
157 #[stable(feature = "rust1", since = "1.0.0")]
158 pub unsafe fn write<T>(dst: *mut T, src: T) {
159 intrinsics::move_val_init(&mut *dst, src)
162 #[stable(feature = "rust1", since = "1.0.0")]
163 #[lang = "const_ptr"]
164 impl<T: ?Sized> *const T {
165 /// Returns true if the pointer is null.
166 #[stable(feature = "rust1", since = "1.0.0")]
168 pub fn is_null(self) -> bool where T: Sized {
172 /// Returns `None` if the pointer is null, or else returns a reference to
173 /// the value wrapped in `Some`.
177 /// While this method and its mutable counterpart are useful for
178 /// null-safety, it is important to note that this is still an unsafe
179 /// operation because the returned value could be pointing to invalid
181 #[unstable(feature = "ptr_as_ref",
182 reason = "Option is not clearly the right return type, and we \
183 may want to tie the return lifetime to a borrow of \
187 pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
195 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
196 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
200 /// Both the starting and resulting pointer must be either in bounds or one
201 /// byte past the end of an allocated object. If either pointer is out of
202 /// bounds or arithmetic overflow occurs then
203 /// any further use of the returned value will result in undefined behavior.
204 #[stable(feature = "rust1", since = "1.0.0")]
206 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
207 intrinsics::offset(self, count)
211 #[stable(feature = "rust1", since = "1.0.0")]
213 impl<T: ?Sized> *mut T {
214 /// Returns true if the pointer is null.
215 #[stable(feature = "rust1", since = "1.0.0")]
217 pub fn is_null(self) -> bool where T: Sized {
221 /// Returns `None` if the pointer is null, or else returns a reference to
222 /// the value wrapped in `Some`.
226 /// While this method and its mutable counterpart are useful for
227 /// null-safety, it is important to note that this is still an unsafe
228 /// operation because the returned value could be pointing to invalid
230 #[unstable(feature = "ptr_as_ref",
231 reason = "Option is not clearly the right return type, and we \
232 may want to tie the return lifetime to a borrow of \
236 pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
244 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
245 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
249 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
250 /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
251 /// the pointer is used.
252 #[stable(feature = "rust1", since = "1.0.0")]
254 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
255 intrinsics::offset(self, count) as *mut T
258 /// Returns `None` if the pointer is null, or else returns a mutable
259 /// reference to the value wrapped in `Some`.
263 /// As with `as_ref`, this is unsafe because it cannot verify the validity
264 /// of the returned pointer.
265 #[unstable(feature = "ptr_as_ref",
266 reason = "return value does not necessarily convey all possible \
270 pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> where T: Sized {
279 // Equality for pointers
280 #[stable(feature = "rust1", since = "1.0.0")]
281 impl<T: ?Sized> PartialEq for *const T {
283 fn eq(&self, other: &*const T) -> bool { *self == *other }
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl<T: ?Sized> Eq for *const T {}
289 #[stable(feature = "rust1", since = "1.0.0")]
290 impl<T: ?Sized> PartialEq for *mut T {
292 fn eq(&self, other: &*mut T) -> bool { *self == *other }
295 #[stable(feature = "rust1", since = "1.0.0")]
296 impl<T: ?Sized> Eq for *mut T {}
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl<T: ?Sized> Clone for *const T {
301 fn clone(&self) -> *const T {
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<T: ?Sized> Clone for *mut T {
309 fn clone(&self) -> *mut T {
314 // Impls for function pointers
315 macro_rules! fnptr_impls_safety_abi {
316 ($FnTy: ty, $($Arg: ident),*) => {
317 #[stable(feature = "rust1", since = "1.0.0")]
318 impl<Ret, $($Arg),*> Clone for $FnTy {
320 fn clone(&self) -> Self {
325 #[stable(feature = "fnptr_impls", since = "1.4.0")]
326 impl<Ret, $($Arg),*> PartialEq for $FnTy {
328 fn eq(&self, other: &Self) -> bool {
329 *self as usize == *other as usize
333 #[stable(feature = "fnptr_impls", since = "1.4.0")]
334 impl<Ret, $($Arg),*> Eq for $FnTy {}
336 #[stable(feature = "fnptr_impls", since = "1.4.0")]
337 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
339 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
340 (*self as usize).partial_cmp(&(*other as usize))
344 #[stable(feature = "fnptr_impls", since = "1.4.0")]
345 impl<Ret, $($Arg),*> Ord for $FnTy {
347 fn cmp(&self, other: &Self) -> Ordering {
348 (*self as usize).cmp(&(*other as usize))
352 #[stable(feature = "fnptr_impls", since = "1.4.0")]
353 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
354 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
355 state.write_usize(*self as usize)
359 #[stable(feature = "fnptr_impls", since = "1.4.0")]
360 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
361 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
362 fmt::Pointer::fmt(&(*self as *const ()), f)
366 #[stable(feature = "fnptr_impls", since = "1.4.0")]
367 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
368 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
369 fmt::Pointer::fmt(&(*self as *const ()), f)
375 macro_rules! fnptr_impls_args {
376 ($($Arg: ident),*) => {
377 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
378 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
379 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
380 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
384 fnptr_impls_args! { }
385 fnptr_impls_args! { A }
386 fnptr_impls_args! { A, B }
387 fnptr_impls_args! { A, B, C }
388 fnptr_impls_args! { A, B, C, D }
389 fnptr_impls_args! { A, B, C, D, E }
390 fnptr_impls_args! { A, B, C, D, E, F }
391 fnptr_impls_args! { A, B, C, D, E, F, G }
392 fnptr_impls_args! { A, B, C, D, E, F, G, H }
393 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
394 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
395 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
396 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
398 // Comparison for pointers
399 #[stable(feature = "rust1", since = "1.0.0")]
400 impl<T: ?Sized> Ord for *const T {
402 fn cmp(&self, other: &*const T) -> Ordering {
405 } else if self == other {
413 #[stable(feature = "rust1", since = "1.0.0")]
414 impl<T: ?Sized> PartialOrd for *const T {
416 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
417 Some(self.cmp(other))
421 fn lt(&self, other: &*const T) -> bool { *self < *other }
424 fn le(&self, other: &*const T) -> bool { *self <= *other }
427 fn gt(&self, other: &*const T) -> bool { *self > *other }
430 fn ge(&self, other: &*const T) -> bool { *self >= *other }
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl<T: ?Sized> Ord for *mut T {
436 fn cmp(&self, other: &*mut T) -> Ordering {
439 } else if self == other {
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl<T: ?Sized> PartialOrd for *mut T {
450 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
451 Some(self.cmp(other))
455 fn lt(&self, other: &*mut T) -> bool { *self < *other }
458 fn le(&self, other: &*mut T) -> bool { *self <= *other }
461 fn gt(&self, other: &*mut T) -> bool { *self > *other }
464 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
467 /// A wrapper around a raw `*mut T` that indicates that the possessor
468 /// of this wrapper owns the referent. This in turn implies that the
469 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
470 /// `*mut T` (which conveys no particular ownership semantics). It
471 /// also implies that the referent of the pointer should not be
472 /// modified without a unique path to the `Unique` reference. Useful
473 /// for building abstractions like `Vec<T>` or `Box<T>`, which
474 /// internally use raw pointers to manage the memory that they own.
475 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
477 pub struct Unique<T: ?Sized> {
478 pointer: NonZero<*const T>,
479 // NOTE: this marker has no consequences for variance, but is necessary
480 // for dropck to understand that we logically own a `T`.
483 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
484 _marker: PhantomData<T>,
487 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
488 /// reference is unaliased. Note that this aliasing invariant is
489 /// unenforced by the type system; the abstraction using the
490 /// `Unique` must enforce it.
491 #[unstable(feature = "unique", issue = "27730")]
492 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
494 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
495 /// reference is unaliased. Note that this aliasing invariant is
496 /// unenforced by the type system; the abstraction using the
497 /// `Unique` must enforce it.
498 #[unstable(feature = "unique", issue = "27730")]
499 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
502 macro_rules! unique_new {
504 /// Creates a new `Unique`.
505 pub unsafe fn new(ptr: *mut T) -> Unique<T> {
506 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
511 macro_rules! unique_new {
513 /// Creates a new `Unique`.
514 pub unsafe const fn new(ptr: *mut T) -> Unique<T> {
515 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
520 #[unstable(feature = "unique", issue = "27730")]
521 impl<T: ?Sized> Unique<T> {
524 /// Dereferences the content.
525 pub unsafe fn get(&self) -> &T {
529 /// Mutably dereferences the content.
530 pub unsafe fn get_mut(&mut self) -> &mut T {
535 #[unstable(feature = "unique", issue= "27730")]
536 impl<T:?Sized> Deref for Unique<T> {
537 type Target = *mut T;
540 fn deref(&self) -> &*mut T {
541 unsafe { mem::transmute(&*self.pointer) }
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl<T> fmt::Pointer for Unique<T> {
547 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
548 fmt::Pointer::fmt(&*self.pointer, f)
552 /// A wrapper around a raw `*mut T` that indicates that the possessor
553 /// of this wrapper has shared ownership of the referent. Useful for
554 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
555 /// use raw pointers to manage the memory that they own.
556 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
558 pub struct Shared<T: ?Sized> {
559 pointer: NonZero<*const T>,
560 // NOTE: this marker has no consequences for variance, but is necessary
561 // for dropck to understand that we logically own a `T`.
564 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
565 _marker: PhantomData<T>,
568 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
569 // NB: This impl is unnecessary, but should provide better error messages.
570 #[unstable(feature = "shared", issue = "27730")]
571 impl<T: ?Sized> !Send for Shared<T> { }
573 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
574 // NB: This impl is unnecessary, but should provide better error messages.
575 #[unstable(feature = "shared", issue = "27730")]
576 impl<T: ?Sized> !Sync for Shared<T> { }
578 #[unstable(feature = "shared", issue = "27730")]
579 impl<T: ?Sized> Shared<T> {
580 /// Creates a new `Shared`.
581 pub unsafe fn new(ptr: *mut T) -> Self {
582 Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
586 #[unstable(feature = "shared", issue = "27730")]
587 impl<T: ?Sized> Clone for Shared<T> {
588 fn clone(&self) -> Self {
593 #[unstable(feature = "shared", issue = "27730")]
594 impl<T: ?Sized> Copy for Shared<T> { }
596 #[cfg(not(stage0))] // remove cfg after new snapshot
597 #[unstable(feature = "shared", issue = "27730")]
598 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
600 #[unstable(feature = "shared", issue = "27730")]
601 impl<T: ?Sized> Deref for Shared<T> {
602 type Target = *mut T;
605 fn deref(&self) -> &*mut T {
606 unsafe { mem::transmute(&*self.pointer) }
610 #[unstable(feature = "shared", issue = "27730")]
611 impl<T> fmt::Pointer for Shared<T> {
612 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
613 fmt::Pointer::fmt(&*self.pointer, f)