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")]
24 use option::Option::{self, Some, None};
25 use marker::{PhantomData, Send, Sized, Sync};
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 /// deinitialising 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 /// Beyond accepting a raw pointer, this operation is unsafe because it does
149 /// not drop the contents of `dst`. This could leak allocations or resources,
150 /// so care must be taken not to overwrite an object that should be dropped.
152 /// This is appropriate for initializing uninitialized memory, or overwriting
153 /// memory that has previously been `read` from.
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub unsafe fn write<T>(dst: *mut T, src: T) {
157 intrinsics::move_val_init(&mut *dst, src)
160 #[stable(feature = "rust1", since = "1.0.0")]
161 #[lang = "const_ptr"]
162 impl<T: ?Sized> *const T {
163 /// Returns true if the pointer is null.
164 #[stable(feature = "rust1", since = "1.0.0")]
166 pub fn is_null(self) -> bool where T: Sized {
170 /// Returns `None` if the pointer is null, or else returns a reference to
171 /// the value wrapped in `Some`.
175 /// While this method and its mutable counterpart are useful for
176 /// null-safety, it is important to note that this is still an unsafe
177 /// operation because the returned value could be pointing to invalid
179 #[unstable(feature = "ptr_as_ref",
180 reason = "Option is not clearly the right return type, and we \
181 may want to tie the return lifetime to a borrow of \
185 pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
193 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
194 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
198 /// Both the starting and resulting pointer must be either in bounds or one
199 /// byte past the end of an allocated object. If either pointer is out of
200 /// bounds or arithmetic overflow occurs then
201 /// any further use of the returned value will result in undefined behavior.
202 #[stable(feature = "rust1", since = "1.0.0")]
204 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
205 intrinsics::offset(self, count)
209 #[stable(feature = "rust1", since = "1.0.0")]
211 impl<T: ?Sized> *mut T {
212 /// Returns true if the pointer is null.
213 #[stable(feature = "rust1", since = "1.0.0")]
215 pub fn is_null(self) -> bool where T: Sized {
219 /// Returns `None` if the pointer is null, or else returns a reference to
220 /// the value wrapped in `Some`.
224 /// While this method and its mutable counterpart are useful for
225 /// null-safety, it is important to note that this is still an unsafe
226 /// operation because the returned value could be pointing to invalid
228 #[unstable(feature = "ptr_as_ref",
229 reason = "Option is not clearly the right return type, and we \
230 may want to tie the return lifetime to a borrow of \
234 pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
242 /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
243 /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
247 /// The offset must be in-bounds of the object, or one-byte-past-the-end.
248 /// Otherwise `offset` invokes Undefined Behaviour, regardless of whether
249 /// the pointer is used.
250 #[stable(feature = "rust1", since = "1.0.0")]
252 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
253 intrinsics::offset(self, count) as *mut T
256 /// Returns `None` if the pointer is null, or else returns a mutable
257 /// reference to the value wrapped in `Some`.
261 /// As with `as_ref`, this is unsafe because it cannot verify the validity
262 /// of the returned pointer.
263 #[unstable(feature = "ptr_as_ref",
264 reason = "return value does not necessarily convey all possible \
268 pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> where T: Sized {
277 // Equality for pointers
278 #[stable(feature = "rust1", since = "1.0.0")]
279 impl<T: ?Sized> PartialEq for *const T {
281 fn eq(&self, other: &*const T) -> bool { *self == *other }
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl<T: ?Sized> Eq for *const T {}
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<T: ?Sized> PartialEq for *mut T {
290 fn eq(&self, other: &*mut T) -> bool { *self == *other }
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl<T: ?Sized> Eq for *mut T {}
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<T: ?Sized> Clone for *const T {
299 fn clone(&self) -> *const T {
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl<T: ?Sized> Clone for *mut T {
307 fn clone(&self) -> *mut T {
312 // Impls for function pointers
313 macro_rules! fnptr_impls_safety_abi {
314 ($FnTy: ty, $($Arg: ident),*) => {
315 #[stable(feature = "rust1", since = "1.0.0")]
316 impl<Ret, $($Arg),*> Clone for $FnTy {
318 fn clone(&self) -> Self {
323 #[stable(feature = "fnptr_impls", since = "1.4.0")]
324 impl<Ret, $($Arg),*> PartialEq for $FnTy {
326 fn eq(&self, other: &Self) -> bool {
327 *self as usize == *other as usize
331 #[stable(feature = "fnptr_impls", since = "1.4.0")]
332 impl<Ret, $($Arg),*> Eq for $FnTy {}
334 #[stable(feature = "fnptr_impls", since = "1.4.0")]
335 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
337 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
338 (*self as usize).partial_cmp(&(*other as usize))
342 #[stable(feature = "fnptr_impls", since = "1.4.0")]
343 impl<Ret, $($Arg),*> Ord for $FnTy {
345 fn cmp(&self, other: &Self) -> Ordering {
346 (*self as usize).cmp(&(*other as usize))
350 #[stable(feature = "fnptr_impls", since = "1.4.0")]
351 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
352 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
353 state.write_usize(*self as usize)
357 #[stable(feature = "fnptr_impls", since = "1.4.0")]
358 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
360 fmt::Pointer::fmt(&(*self as *const ()), f)
364 #[stable(feature = "fnptr_impls", since = "1.4.0")]
365 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
366 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
367 fmt::Pointer::fmt(&(*self as *const ()), f)
373 macro_rules! fnptr_impls_args {
374 ($($Arg: ident),*) => {
375 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
376 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
377 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
378 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
382 fnptr_impls_args! { }
383 fnptr_impls_args! { A }
384 fnptr_impls_args! { A, B }
385 fnptr_impls_args! { A, B, C }
386 fnptr_impls_args! { A, B, C, D }
387 fnptr_impls_args! { A, B, C, D, E }
388 fnptr_impls_args! { A, B, C, D, E, F }
389 fnptr_impls_args! { A, B, C, D, E, F, G }
390 fnptr_impls_args! { A, B, C, D, E, F, G, H }
391 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
392 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
393 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
394 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
396 // Comparison for pointers
397 #[stable(feature = "rust1", since = "1.0.0")]
398 impl<T: ?Sized> Ord for *const T {
400 fn cmp(&self, other: &*const T) -> Ordering {
403 } else if self == other {
411 #[stable(feature = "rust1", since = "1.0.0")]
412 impl<T: ?Sized> PartialOrd for *const T {
414 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
415 Some(self.cmp(other))
419 fn lt(&self, other: &*const T) -> bool { *self < *other }
422 fn le(&self, other: &*const T) -> bool { *self <= *other }
425 fn gt(&self, other: &*const T) -> bool { *self > *other }
428 fn ge(&self, other: &*const T) -> bool { *self >= *other }
431 #[stable(feature = "rust1", since = "1.0.0")]
432 impl<T: ?Sized> Ord for *mut T {
434 fn cmp(&self, other: &*mut T) -> Ordering {
437 } else if self == other {
445 #[stable(feature = "rust1", since = "1.0.0")]
446 impl<T: ?Sized> PartialOrd for *mut T {
448 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
449 Some(self.cmp(other))
453 fn lt(&self, other: &*mut T) -> bool { *self < *other }
456 fn le(&self, other: &*mut T) -> bool { *self <= *other }
459 fn gt(&self, other: &*mut T) -> bool { *self > *other }
462 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
465 /// A wrapper around a raw `*mut T` that indicates that the possessor
466 /// of this wrapper owns the referent. This in turn implies that the
467 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
468 /// `*mut T` (which conveys no particular ownership semantics). It
469 /// also implies that the referent of the pointer should not be
470 /// modified without a unique path to the `Unique` reference. Useful
471 /// for building abstractions like `Vec<T>` or `Box<T>`, which
472 /// internally use raw pointers to manage the memory that they own.
473 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
475 pub struct Unique<T: ?Sized> {
476 pointer: NonZero<*const T>,
477 // NOTE: this marker has no consequences for variance, but is necessary
478 // for dropck to understand that we logically own a `T`.
481 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
482 _marker: PhantomData<T>,
485 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
486 /// reference is unaliased. Note that this aliasing invariant is
487 /// unenforced by the type system; the abstraction using the
488 /// `Unique` must enforce it.
489 #[unstable(feature = "unique", issue = "27730")]
490 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
492 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
493 /// reference is unaliased. Note that this aliasing invariant is
494 /// unenforced by the type system; the abstraction using the
495 /// `Unique` must enforce it.
496 #[unstable(feature = "unique", issue = "27730")]
497 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
499 #[unstable(feature = "unique", issue = "27730")]
500 impl<T: ?Sized> Unique<T> {
501 /// Creates a new `Unique`.
502 pub unsafe fn new(ptr: *mut T) -> Unique<T> {
503 Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
506 /// Dereferences the content.
507 pub unsafe fn get(&self) -> &T {
511 /// Mutably dereferences the content.
512 pub unsafe fn get_mut(&mut self) -> &mut T {
517 #[unstable(feature = "unique", issue= "27730")]
518 impl<T:?Sized> Deref for Unique<T> {
519 type Target = *mut T;
522 fn deref(&self) -> &*mut T {
523 unsafe { mem::transmute(&*self.pointer) }
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl<T> fmt::Pointer for Unique<T> {
529 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
530 fmt::Pointer::fmt(&*self.pointer, f)