]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[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,
19 //! the [`is_null`](trait.PtrExt.html#tymethod.is_null)
20 //! methods of the [`PtrExt` trait](trait.PtrExt.html) to check for null.
21 //! The `PtrExt` trait is imported by the prelude, so `is_null` etc.
22 //! work everywhere. The `PtrExt` also defines the `offset` method,
23 //! for pointer math.
24 //!
25 //! # Common ways to create unsafe pointers
26 //!
27 //! ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
28 //!
29 //! ```
30 //! let my_num: i32 = 10;
31 //! let my_num_ptr: *const i32 = &my_num;
32 //! let mut my_speed: i32 = 88;
33 //! let my_speed_ptr: *mut i32 = &mut my_speed;
34 //! ```
35 //!
36 //! This does not take ownership of the original allocation
37 //! and requires no resource management later,
38 //! but you must not use the pointer after its lifetime.
39 //!
40 //! ## 2. Transmute an owned box (`Box<T>`).
41 //!
42 //! The `transmute` function takes, by value, whatever it's given
43 //! and returns it as whatever type is requested, as long as the
44 //! types are the same size. Because `Box<T>` and `*mut T` have the same
45 //! representation they can be trivially,
46 //! though unsafely, transformed from one type to the other.
47 //!
48 //! ```
49 //! use std::mem;
50 //!
51 //! unsafe {
52 //!     let my_num: Box<i32> = Box::new(10);
53 //!     let my_num: *const i32 = mem::transmute(my_num);
54 //!     let my_speed: Box<i32> = Box::new(88);
55 //!     let my_speed: *mut i32 = mem::transmute(my_speed);
56 //!
57 //!     // By taking ownership of the original `Box<T>` though
58 //!     // we are obligated to transmute it back later to be destroyed.
59 //!     drop(mem::transmute::<_, Box<i32>>(my_speed));
60 //!     drop(mem::transmute::<_, Box<i32>>(my_num));
61 //! }
62 //! ```
63 //!
64 //! Note that here the call to `drop` is for clarity - it indicates
65 //! that we are done with the given value and it should be destroyed.
66 //!
67 //! ## 3. Get it from C.
68 //!
69 //! ```
70 //! extern crate libc;
71 //!
72 //! use std::mem;
73 //!
74 //! fn main() {
75 //!     unsafe {
76 //!         let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>() as libc::size_t) as *mut i32;
77 //!         if my_num.is_null() {
78 //!             panic!("failed to allocate memory");
79 //!         }
80 //!         libc::free(my_num as *mut libc::c_void);
81 //!     }
82 //! }
83 //! ```
84 //!
85 //! Usually you wouldn't literally use `malloc` and `free` from Rust,
86 //! but C APIs hand out a lot of pointers generally, so are a common source
87 //! of unsafe pointers in Rust.
88
89 #![stable(feature = "rust1", since = "1.0.0")]
90
91 use mem;
92 use clone::Clone;
93 use intrinsics;
94 use option::Option::{self, Some, None};
95 use marker::{self, Send, Sized, Sync};
96
97 use cmp::{PartialEq, Eq, Ord, PartialOrd};
98 use cmp::Ordering::{self, Less, Equal, Greater};
99
100 // FIXME #19649: intrinsic docs don't render, so these have no docs :(
101
102 #[unstable(feature = "core")]
103 pub use intrinsics::copy_nonoverlapping_memory;
104
105 #[unstable(feature = "core")]
106 pub use intrinsics::copy_memory;
107
108 #[unstable(feature = "core",
109            reason = "uncertain about naming and semantics")]
110 pub use intrinsics::set_memory;
111
112
113 /// Creates a null raw pointer.
114 ///
115 /// # Examples
116 ///
117 /// ```
118 /// use std::ptr;
119 ///
120 /// let p: *const i32 = ptr::null();
121 /// assert!(p.is_null());
122 /// ```
123 #[inline]
124 #[stable(feature = "rust1", since = "1.0.0")]
125 pub fn null<T>() -> *const T { 0 as *const T }
126
127 /// Creates a null mutable raw pointer.
128 ///
129 /// # Examples
130 ///
131 /// ```
132 /// use std::ptr;
133 ///
134 /// let p: *mut i32 = ptr::null_mut();
135 /// assert!(p.is_null());
136 /// ```
137 #[inline]
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub fn null_mut<T>() -> *mut T { 0 as *mut T }
140
141 /// Zeroes out `count * size_of::<T>` bytes of memory at `dst`. `count` may be
142 /// `0`.
143 ///
144 /// # Safety
145 ///
146 /// Beyond accepting a raw pointer, this is unsafe because it will not drop the
147 /// contents of `dst`, and may be used to create invalid instances of `T`.
148 #[inline]
149 #[unstable(feature = "core",
150            reason = "may play a larger role in std::ptr future extensions")]
151 pub unsafe fn zero_memory<T>(dst: *mut T, count: usize) {
152     set_memory(dst, 0, count);
153 }
154
155 /// Swaps the values at two mutable locations of the same type, without
156 /// deinitialising either. They may overlap, unlike `mem::swap` which is
157 /// otherwise equivalent.
158 ///
159 /// # Safety
160 ///
161 /// This is only unsafe because it accepts a raw pointer.
162 #[inline]
163 #[stable(feature = "rust1", since = "1.0.0")]
164 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
165     // Give ourselves some scratch space to work with
166     let mut tmp: T = mem::uninitialized();
167     let t: *mut T = &mut tmp;
168
169     // Perform the swap
170     copy_nonoverlapping_memory(t, &*x, 1);
171     copy_memory(x, &*y, 1); // `x` and `y` may overlap
172     copy_nonoverlapping_memory(y, &*t, 1);
173
174     // y and t now point to the same thing, but we need to completely forget `tmp`
175     // because it's no longer relevant.
176     mem::forget(tmp);
177 }
178
179 /// Replaces the value at `dest` with `src`, returning the old
180 /// value, without dropping either.
181 ///
182 /// # Safety
183 ///
184 /// This is only unsafe because it accepts a raw pointer.
185 /// Otherwise, this operation is identical to `mem::replace`.
186 #[inline]
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
189     mem::swap(mem::transmute(dest), &mut src); // cannot overlap
190     src
191 }
192
193 /// Reads the value from `src` without moving it. This leaves the
194 /// memory in `src` unchanged.
195 ///
196 /// # Safety
197 ///
198 /// Beyond accepting a raw pointer, this is unsafe because it semantically
199 /// moves the value out of `src` without preventing further usage of `src`.
200 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
201 /// `src` is not used before the data is overwritten again (e.g. with `write`,
202 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
203 /// because it will attempt to drop the value previously at `*src`.
204 #[inline(always)]
205 #[stable(feature = "rust1", since = "1.0.0")]
206 pub unsafe fn read<T>(src: *const T) -> T {
207     let mut tmp: T = mem::uninitialized();
208     copy_nonoverlapping_memory(&mut tmp, src, 1);
209     tmp
210 }
211
212 /// Reads the value from `src` and nulls it out without dropping it.
213 ///
214 /// # Safety
215 ///
216 /// This is unsafe for the same reasons that `read` is unsafe.
217 #[inline(always)]
218 #[unstable(feature = "core",
219            reason = "may play a larger role in std::ptr future extensions")]
220 pub unsafe fn read_and_zero<T>(dest: *mut T) -> T {
221     // Copy the data out from `dest`:
222     let tmp = read(&*dest);
223
224     // Now zero out `dest`:
225     zero_memory(dest, 1);
226
227     tmp
228 }
229
230 /// Overwrites a memory location with the given value without reading or
231 /// dropping the old value.
232 ///
233 /// # Safety
234 ///
235 /// Beyond accepting a raw pointer, this operation is unsafe because it does
236 /// not drop the contents of `dst`. This could leak allocations or resources,
237 /// so care must be taken not to overwrite an object that should be dropped.
238 ///
239 /// This is appropriate for initializing uninitialized memory, or overwriting
240 /// memory that has previously been `read` from.
241 #[inline]
242 #[stable(feature = "rust1", since = "1.0.0")]
243 pub unsafe fn write<T>(dst: *mut T, src: T) {
244     intrinsics::move_val_init(&mut *dst, src)
245 }
246
247 /// Methods on raw pointers
248 #[stable(feature = "rust1", since = "1.0.0")]
249 pub trait PtrExt: Sized {
250     type Target;
251
252     /// Returns true if the pointer is null.
253     #[stable(feature = "rust1", since = "1.0.0")]
254     fn is_null(self) -> bool;
255
256     /// Returns `None` if the pointer is null, or else returns a reference to
257     /// the value wrapped in `Some`.
258     ///
259     /// # Safety
260     ///
261     /// While this method and its mutable counterpart are useful for
262     /// null-safety, it is important to note that this is still an unsafe
263     /// operation because the returned value could be pointing to invalid
264     /// memory.
265     #[unstable(feature = "core",
266                reason = "Option is not clearly the right return type, and we may want \
267                          to tie the return lifetime to a borrow of the raw pointer")]
268     unsafe fn as_ref<'a>(&self) -> Option<&'a Self::Target>;
269
270     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
271     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
272     ///
273     /// # Safety
274     ///
275     /// The offset must be in-bounds of the object, or one-byte-past-the-end.
276     /// Otherwise `offset` invokes Undefined Behaviour, regardless of whether
277     /// the pointer is used.
278     #[stable(feature = "rust1", since = "1.0.0")]
279     unsafe fn offset(self, count: isize) -> Self;
280 }
281
282 /// Methods on mutable raw pointers
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub trait MutPtrExt {
285     type Target;
286
287     /// Returns `None` if the pointer is null, or else returns a mutable
288     /// reference to the value wrapped in `Some`.
289     ///
290     /// # Safety
291     ///
292     /// As with `as_ref`, this is unsafe because it cannot verify the validity
293     /// of the returned pointer.
294     #[unstable(feature = "core",
295                reason = "Option is not clearly the right return type, and we may want \
296                          to tie the return lifetime to a borrow of the raw pointer")]
297     unsafe fn as_mut<'a>(&self) -> Option<&'a mut Self::Target>;
298 }
299
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl<T> PtrExt for *const T {
302     type Target = T;
303
304     #[inline]
305     #[stable(feature = "rust1", since = "1.0.0")]
306     fn is_null(self) -> bool { self as usize == 0 }
307
308     #[inline]
309     #[stable(feature = "rust1", since = "1.0.0")]
310     unsafe fn offset(self, count: isize) -> *const T {
311         intrinsics::offset(self, count)
312     }
313
314     #[inline]
315     #[unstable(feature = "core",
316                reason = "return value does not necessarily convey all possible \
317                          information")]
318     unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
319         if self.is_null() {
320             None
321         } else {
322             Some(&**self)
323         }
324     }
325 }
326
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl<T> PtrExt for *mut T {
329     type Target = T;
330
331     #[inline]
332     #[stable(feature = "rust1", since = "1.0.0")]
333     fn is_null(self) -> bool { self as usize == 0 }
334
335     #[inline]
336     #[stable(feature = "rust1", since = "1.0.0")]
337     unsafe fn offset(self, count: isize) -> *mut T {
338         intrinsics::offset(self, count) as *mut T
339     }
340
341     #[inline]
342     #[unstable(feature = "core",
343                reason = "return value does not necessarily convey all possible \
344                          information")]
345     unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
346         if self.is_null() {
347             None
348         } else {
349             Some(&**self)
350         }
351     }
352 }
353
354 #[stable(feature = "rust1", since = "1.0.0")]
355 impl<T> MutPtrExt for *mut T {
356     type Target = T;
357
358     #[inline]
359     #[unstable(feature = "core",
360                reason = "return value does not necessarily convey all possible \
361                          information")]
362     unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> {
363         if self.is_null() {
364             None
365         } else {
366             Some(&mut **self)
367         }
368     }
369 }
370
371 // Equality for pointers
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl<T> PartialEq for *const T {
374     #[inline]
375     fn eq(&self, other: &*const T) -> bool {
376         *self == *other
377     }
378     #[inline]
379     fn ne(&self, other: &*const T) -> bool { !self.eq(other) }
380 }
381
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl<T> Eq for *const T {}
384
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl<T> PartialEq for *mut T {
387     #[inline]
388     fn eq(&self, other: &*mut T) -> bool {
389         *self == *other
390     }
391     #[inline]
392     fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
393 }
394
395 #[stable(feature = "rust1", since = "1.0.0")]
396 impl<T> Eq for *mut T {}
397
398 #[stable(feature = "rust1", since = "1.0.0")]
399 impl<T> 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> 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> 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> 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> 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> 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
521 /// raw `*mut T` (which conveys no particular ownership semantics).
522 /// Useful for building abstractions like `Vec<T>` or `Box<T>`, which
523 /// internally use raw pointers to manage the memory that they own.
524 #[unstable(feature = "core", reason = "recently added to this module")]
525 pub struct Unique<T: ?Sized> {
526     /// The wrapped `*mut T`.
527     pub ptr: *mut T,
528     _own: marker::PhantomData<T>,
529 }
530
531 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
532 /// reference is unaliased. Note that this aliasing invariant is
533 /// unenforced by the type system; the abstraction using the
534 /// `Unique` must enforce it.
535 #[unstable(feature = "core", reason = "recently added to this module")]
536 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
537
538 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
539 /// reference is unaliased. Note that this aliasing invariant is
540 /// unenforced by the type system; the abstraction using the
541 /// `Unique` must enforce it.
542 #[unstable(feature = "core", reason = "recently added to this module")]
543 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
544
545 impl<T> Unique<T> {
546     /// Returns a null Unique.
547     #[unstable(feature = "core",
548                reason = "recently added to this module")]
549     pub fn null() -> Unique<T> {
550         Unique(null_mut())
551     }
552
553     /// Return an (unsafe) pointer into the memory owned by `self`.
554     #[unstable(feature = "core",
555                reason = "recently added to this module")]
556     pub unsafe fn offset(self, offset: isize) -> *mut T {
557         self.ptr.offset(offset)
558     }
559 }
560
561 /// Creates a `Unique` wrapped around `ptr`, taking ownership of the
562 /// data referenced by `ptr`.
563 #[allow(non_snake_case)]
564 pub fn Unique<T: ?Sized>(ptr: *mut T) -> Unique<T> {
565     Unique { ptr: ptr, _own: marker::PhantomData }
566 }