]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
Auto merge of #24177 - alexcrichton:rustdoc, r=aturon
[rust.git] / src / libcore / ptr.rs
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.
4 //
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.
10
11 // FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory
12
13 //! Operations on unsafe pointers, `*const T`, and `*mut T`.
14 //!
15 //! Working with unsafe pointers in Rust is uncommon,
16 //! typically limited to a few patterns.
17 //!
18 //! Use the [`null` function](fn.null.html) to create null pointers, and
19 //! the `is_null` method of the `*const T` type  to check for null.
20 //! The `*const T` type also defines the `offset` method, for pointer math.
21 //!
22 //! # Common ways to create unsafe pointers
23 //!
24 //! ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
25 //!
26 //! ```
27 //! let my_num: i32 = 10;
28 //! let my_num_ptr: *const i32 = &my_num;
29 //! let mut my_speed: i32 = 88;
30 //! let my_speed_ptr: *mut i32 = &mut my_speed;
31 //! ```
32 //!
33 //! To get a pointer to a boxed value, dereference the box:
34 //!
35 //! ```
36 //! let my_num: Box<i32> = Box::new(10);
37 //! let my_num_ptr: *const i32 = &*my_num;
38 //! let mut my_speed: Box<i32> = Box::new(88);
39 //! let my_speed_ptr: *mut i32 = &mut *my_speed;
40 //! ```
41 //!
42 //! This does not take ownership of the original allocation
43 //! and requires no resource management later,
44 //! but you must not use the pointer after its lifetime.
45 //!
46 //! ## 2. Consume a box (`Box<T>`).
47 //!
48 //! The `into_raw` function consumes a box and returns
49 //! the raw pointer. It doesn't destroy `T` or deallocate any memory.
50 //!
51 //! ```
52 //! # #![feature(alloc)]
53 //! use std::boxed;
54 //!
55 //! unsafe {
56 //!     let my_speed: Box<i32> = Box::new(88);
57 //!     let my_speed: *mut i32 = boxed::into_raw(my_speed);
58 //!
59 //!     // By taking ownership of the original `Box<T>` though
60 //!     // we are obligated to put it together later to be destroyed.
61 //!     drop(Box::from_raw(my_speed));
62 //! }
63 //! ```
64 //!
65 //! Note that here the call to `drop` is for clarity - it indicates
66 //! that we are done with the given value and it should be destroyed.
67 //!
68 //! ## 3. Get it from C.
69 //!
70 //! ```
71 //! # #![feature(libc)]
72 //! extern crate libc;
73 //!
74 //! use std::mem;
75 //!
76 //! fn main() {
77 //!     unsafe {
78 //!         let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>() as libc::size_t) as *mut i32;
79 //!         if my_num.is_null() {
80 //!             panic!("failed to allocate memory");
81 //!         }
82 //!         libc::free(my_num as *mut libc::c_void);
83 //!     }
84 //! }
85 //! ```
86 //!
87 //! Usually you wouldn't literally use `malloc` and `free` from Rust,
88 //! but C APIs hand out a lot of pointers generally, so are a common source
89 //! of unsafe pointers in Rust.
90
91 #![stable(feature = "rust1", since = "1.0.0")]
92 #![doc(primitive = "pointer")]
93
94 use mem;
95 use clone::Clone;
96 use intrinsics;
97 use ops::Deref;
98 use core::fmt;
99 use option::Option::{self, Some, None};
100 use marker::{PhantomData, Send, Sized, Sync};
101 use nonzero::NonZero;
102
103 use cmp::{PartialEq, Eq, Ord, PartialOrd};
104 use cmp::Ordering::{self, Less, Equal, Greater};
105
106 // FIXME #19649: intrinsic docs don't render, so these have no docs :(
107
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[cfg(not(stage0))]
110 pub use intrinsics::copy_nonoverlapping;
111
112 /// dox
113 #[cfg(stage0)]
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize) {
116     intrinsics::copy_nonoverlapping(dst, src, count)
117 }
118
119 #[stable(feature = "rust1", since = "1.0.0")]
120 #[cfg(not(stage0))]
121 pub use intrinsics::copy;
122
123 /// dox
124 #[cfg(stage0)]
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize) {
127     intrinsics::copy(dst, src, count)
128 }
129
130
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub use intrinsics::write_bytes;
133
134 /// Creates a null raw pointer.
135 ///
136 /// # Examples
137 ///
138 /// ```
139 /// use std::ptr;
140 ///
141 /// let p: *const i32 = ptr::null();
142 /// assert!(p.is_null());
143 /// ```
144 #[inline]
145 #[stable(feature = "rust1", since = "1.0.0")]
146 pub fn null<T>() -> *const T { 0 as *const T }
147
148 /// Creates a null mutable raw pointer.
149 ///
150 /// # Examples
151 ///
152 /// ```
153 /// use std::ptr;
154 ///
155 /// let p: *mut i32 = ptr::null_mut();
156 /// assert!(p.is_null());
157 /// ```
158 #[inline]
159 #[stable(feature = "rust1", since = "1.0.0")]
160 pub fn null_mut<T>() -> *mut T { 0 as *mut T }
161
162 /// Swaps the values at two mutable locations of the same type, without
163 /// deinitialising either. They may overlap, unlike `mem::swap` which is
164 /// otherwise equivalent.
165 ///
166 /// # Safety
167 ///
168 /// This is only unsafe because it accepts a raw pointer.
169 #[inline]
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
172     // Give ourselves some scratch space to work with
173     let mut tmp: T = mem::uninitialized();
174
175     // Perform the swap
176     copy_nonoverlapping(x, &mut tmp, 1);
177     copy(y, x, 1); // `x` and `y` may overlap
178     copy_nonoverlapping(&tmp, y, 1);
179
180     // y and t now point to the same thing, but we need to completely forget `tmp`
181     // because it's no longer relevant.
182     mem::forget(tmp);
183 }
184
185 /// Replaces the value at `dest` with `src`, returning the old
186 /// value, without dropping either.
187 ///
188 /// # Safety
189 ///
190 /// This is only unsafe because it accepts a raw pointer.
191 /// Otherwise, this operation is identical to `mem::replace`.
192 #[inline]
193 #[stable(feature = "rust1", since = "1.0.0")]
194 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
195     mem::swap(mem::transmute(dest), &mut src); // cannot overlap
196     src
197 }
198
199 /// Reads the value from `src` without moving it. This leaves the
200 /// memory in `src` unchanged.
201 ///
202 /// # Safety
203 ///
204 /// Beyond accepting a raw pointer, this is unsafe because it semantically
205 /// moves the value out of `src` without preventing further usage of `src`.
206 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
207 /// `src` is not used before the data is overwritten again (e.g. with `write`,
208 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
209 /// because it will attempt to drop the value previously at `*src`.
210 #[inline(always)]
211 #[stable(feature = "rust1", since = "1.0.0")]
212 pub unsafe fn read<T>(src: *const T) -> T {
213     let mut tmp: T = mem::uninitialized();
214     copy_nonoverlapping(src, &mut tmp, 1);
215     tmp
216 }
217
218 /// Reads the value from `src` and nulls it out without dropping it.
219 ///
220 /// # Safety
221 ///
222 /// This is unsafe for the same reasons that `read` is unsafe.
223 #[inline(always)]
224 #[unstable(feature = "core",
225            reason = "may play a larger role in std::ptr future extensions")]
226 pub unsafe fn read_and_zero<T>(dest: *mut T) -> T {
227     // Copy the data out from `dest`:
228     let tmp = read(&*dest);
229
230     // Now zero out `dest`:
231     write_bytes(dest, 0, 1);
232
233     tmp
234 }
235
236 /// Variant of read_and_zero that writes the specific drop-flag byte
237 /// (which may be more appropriate than zero).
238 #[inline(always)]
239 #[unstable(feature = "core",
240            reason = "may play a larger role in std::ptr future extensions")]
241 pub unsafe fn read_and_drop<T>(dest: *mut T) -> T {
242     // Copy the data out from `dest`:
243     let tmp = read(&*dest);
244
245     // Now mark `dest` as dropped:
246     write_bytes(dest, mem::POST_DROP_U8, 1);
247
248     tmp
249 }
250
251 /// Overwrites a memory location with the given value without reading or
252 /// dropping the old value.
253 ///
254 /// # Safety
255 ///
256 /// Beyond accepting a raw pointer, this operation is unsafe because it does
257 /// not drop the contents of `dst`. This could leak allocations or resources,
258 /// so care must be taken not to overwrite an object that should be dropped.
259 ///
260 /// This is appropriate for initializing uninitialized memory, or overwriting
261 /// memory that has previously been `read` from.
262 #[inline]
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub unsafe fn write<T>(dst: *mut T, src: T) {
265     intrinsics::move_val_init(&mut *dst, src)
266 }
267
268 #[stable(feature = "rust1", since = "1.0.0")]
269 #[lang = "const_ptr"]
270 impl<T: ?Sized> *const T {
271     /// Returns true if the pointer is null.
272     #[stable(feature = "rust1", since = "1.0.0")]
273     #[inline]
274     pub fn is_null(self) -> bool where T: Sized {
275         self == 0 as *const T
276     }
277
278     /// Returns `None` if the pointer is null, or else returns a reference to
279     /// the value wrapped in `Some`.
280     ///
281     /// # Safety
282     ///
283     /// While this method and its mutable counterpart are useful for
284     /// null-safety, it is important to note that this is still an unsafe
285     /// operation because the returned value could be pointing to invalid
286     /// memory.
287     #[unstable(feature = "core",
288                reason = "Option is not clearly the right return type, and we may want \
289                          to tie the return lifetime to a borrow of the raw pointer")]
290     #[inline]
291     pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
292         if self.is_null() {
293             None
294         } else {
295             Some(&**self)
296         }
297     }
298
299     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
300     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
301     ///
302     /// # Safety
303     ///
304     /// The offset must be in-bounds of the object, or one-byte-past-the-end.
305     /// Otherwise `offset` invokes Undefined Behaviour, regardless of whether
306     /// the pointer is used.
307     #[stable(feature = "rust1", since = "1.0.0")]
308     #[inline]
309     pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
310         intrinsics::offset(self, count)
311     }
312 }
313
314 #[stable(feature = "rust1", since = "1.0.0")]
315 #[lang = "mut_ptr"]
316 impl<T: ?Sized> *mut T {
317     /// Returns true if the pointer is null.
318     #[stable(feature = "rust1", since = "1.0.0")]
319     #[inline]
320     pub fn is_null(self) -> bool where T: Sized {
321         self == 0 as *mut T
322     }
323
324     /// Returns `None` if the pointer is null, or else returns a reference to
325     /// the value wrapped in `Some`.
326     ///
327     /// # Safety
328     ///
329     /// While this method and its mutable counterpart are useful for
330     /// null-safety, it is important to note that this is still an unsafe
331     /// operation because the returned value could be pointing to invalid
332     /// memory.
333     #[unstable(feature = "core",
334                reason = "Option is not clearly the right return type, and we may want \
335                          to tie the return lifetime to a borrow of the raw pointer")]
336     #[inline]
337     pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
338         if self.is_null() {
339             None
340         } else {
341             Some(&**self)
342         }
343     }
344
345     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
346     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
347     ///
348     /// # Safety
349     ///
350     /// The offset must be in-bounds of the object, or one-byte-past-the-end.
351     /// Otherwise `offset` invokes Undefined Behaviour, regardless of whether
352     /// the pointer is used.
353     #[stable(feature = "rust1", since = "1.0.0")]
354     #[inline]
355     pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
356         intrinsics::offset(self, count) as *mut T
357     }
358
359     /// Returns `None` if the pointer is null, or else returns a mutable
360     /// reference to the value wrapped in `Some`.
361     ///
362     /// # Safety
363     ///
364     /// As with `as_ref`, this is unsafe because it cannot verify the validity
365     /// of the returned pointer.
366     #[unstable(feature = "core",
367                reason = "return value does not necessarily convey all possible \
368                          information")]
369     #[inline]
370     pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> where T: Sized {
371         if self.is_null() {
372             None
373         } else {
374             Some(&mut **self)
375         }
376     }
377 }
378
379 // Equality for pointers
380 #[stable(feature = "rust1", since = "1.0.0")]
381 impl<T: ?Sized> PartialEq for *const T {
382     #[inline]
383     fn eq(&self, other: &*const T) -> bool { *self == *other }
384 }
385
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl<T: ?Sized> Eq for *const T {}
388
389 #[stable(feature = "rust1", since = "1.0.0")]
390 impl<T: ?Sized> PartialEq for *mut T {
391     #[inline]
392     fn eq(&self, other: &*mut T) -> bool { *self == *other }
393 }
394
395 #[stable(feature = "rust1", since = "1.0.0")]
396 impl<T: ?Sized> Eq for *mut T {}
397
398 #[stable(feature = "rust1", since = "1.0.0")]
399 impl<T: ?Sized> Clone for *const T {
400     #[inline]
401     fn clone(&self) -> *const T {
402         *self
403     }
404 }
405
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl<T: ?Sized> Clone for *mut T {
408     #[inline]
409     fn clone(&self) -> *mut T {
410         *self
411     }
412 }
413
414 // Equality for extern "C" fn pointers
415 mod externfnpointers {
416     use mem;
417     use cmp::PartialEq;
418
419     #[stable(feature = "rust1", since = "1.0.0")]
420     impl<_R> PartialEq for extern "C" fn() -> _R {
421         #[inline]
422         fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
423             let self_: *const () = unsafe { mem::transmute(*self) };
424             let other_: *const () = unsafe { mem::transmute(*other) };
425             self_ == other_
426         }
427     }
428     macro_rules! fnptreq {
429         ($($p:ident),*) => {
430             #[stable(feature = "rust1", since = "1.0.0")]
431             impl<_R,$($p),*> PartialEq for extern "C" fn($($p),*) -> _R {
432                 #[inline]
433                 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
434                     let self_: *const () = unsafe { mem::transmute(*self) };
435
436                     let other_: *const () = unsafe { mem::transmute(*other) };
437                     self_ == other_
438                 }
439             }
440         }
441     }
442     fnptreq! { A }
443     fnptreq! { A,B }
444     fnptreq! { A,B,C }
445     fnptreq! { A,B,C,D }
446     fnptreq! { A,B,C,D,E }
447 }
448
449 // Comparison for pointers
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl<T: ?Sized> Ord for *const T {
452     #[inline]
453     fn cmp(&self, other: &*const T) -> Ordering {
454         if self < other {
455             Less
456         } else if self == other {
457             Equal
458         } else {
459             Greater
460         }
461     }
462 }
463
464 #[stable(feature = "rust1", since = "1.0.0")]
465 impl<T: ?Sized> PartialOrd for *const T {
466     #[inline]
467     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
468         Some(self.cmp(other))
469     }
470
471     #[inline]
472     fn lt(&self, other: &*const T) -> bool { *self < *other }
473
474     #[inline]
475     fn le(&self, other: &*const T) -> bool { *self <= *other }
476
477     #[inline]
478     fn gt(&self, other: &*const T) -> bool { *self > *other }
479
480     #[inline]
481     fn ge(&self, other: &*const T) -> bool { *self >= *other }
482 }
483
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl<T: ?Sized> Ord for *mut T {
486     #[inline]
487     fn cmp(&self, other: &*mut T) -> Ordering {
488         if self < other {
489             Less
490         } else if self == other {
491             Equal
492         } else {
493             Greater
494         }
495     }
496 }
497
498 #[stable(feature = "rust1", since = "1.0.0")]
499 impl<T: ?Sized> PartialOrd for *mut T {
500     #[inline]
501     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
502         Some(self.cmp(other))
503     }
504
505     #[inline]
506     fn lt(&self, other: &*mut T) -> bool { *self < *other }
507
508     #[inline]
509     fn le(&self, other: &*mut T) -> bool { *self <= *other }
510
511     #[inline]
512     fn gt(&self, other: &*mut T) -> bool { *self > *other }
513
514     #[inline]
515     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
516 }
517
518 /// A wrapper around a raw `*mut T` that indicates that the possessor
519 /// of this wrapper owns the referent. This in turn implies that the
520 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
521 /// `*mut T` (which conveys no particular ownership semantics).  It
522 /// also implies that the referent of the pointer should not be
523 /// modified without a unique path to the `Unique` reference. Useful
524 /// for building abstractions like `Vec<T>` or `Box<T>`, which
525 /// internally use raw pointers to manage the memory that they own.
526 #[unstable(feature = "unique")]
527 pub struct Unique<T: ?Sized> {
528     pointer: NonZero<*const T>,
529     _marker: PhantomData<T>,
530 }
531
532 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
533 /// reference is unaliased. Note that this aliasing invariant is
534 /// unenforced by the type system; the abstraction using the
535 /// `Unique` must enforce it.
536 #[unstable(feature = "unique")]
537 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
538
539 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
540 /// reference is unaliased. Note that this aliasing invariant is
541 /// unenforced by the type system; the abstraction using the
542 /// `Unique` must enforce it.
543 #[unstable(feature = "unique")]
544 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
545
546 impl<T: ?Sized> Unique<T> {
547     /// Create a new `Unique`.
548     #[unstable(feature = "unique")]
549     pub unsafe fn new(ptr: *mut T) -> Unique<T> {
550         Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
551     }
552
553     /// Dereference the content.
554     #[unstable(feature = "unique")]
555     pub unsafe fn get(&self) -> &T {
556         &**self.pointer
557     }
558
559     /// Mutably dereference the content.
560     #[unstable(feature = "unique")]
561     pub unsafe fn get_mut(&mut self) -> &mut T {
562         &mut ***self
563     }
564 }
565
566 #[unstable(feature = "unique")]
567 impl<T:?Sized> Deref for Unique<T> {
568     type Target = *mut T;
569
570     #[inline]
571     fn deref<'a>(&'a self) -> &'a *mut T {
572         unsafe { mem::transmute(&*self.pointer) }
573     }
574 }
575
576 #[stable(feature = "rust1", since = "1.0.0")]
577 impl<T> fmt::Pointer for Unique<T> {
578     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
579         fmt::Pointer::fmt(&*self.pointer, f)
580     }
581 }