]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
mk: The beta channel produces things called 'beta'
[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: int = 10;
31 //! let my_num_ptr: *const int = &my_num;
32 //! let mut my_speed: int = 88;
33 //! let my_speed_ptr: *mut int = &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::boxed::Box;
50 //! use std::mem;
51 //!
52 //! unsafe {
53 //!     let my_num: Box<int> = Box::new(10);
54 //!     let my_num: *const int = mem::transmute(my_num);
55 //!     let my_speed: Box<int> = Box::new(88);
56 //!     let my_speed: *mut int = mem::transmute(my_speed);
57 //!
58 //!     // By taking ownership of the original `Box<T>` though
59 //!     // we are obligated to transmute it back later to be destroyed.
60 //!     drop(mem::transmute::<_, Box<int>>(my_speed));
61 //!     drop(mem::transmute::<_, Box<int>>(my_num));
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 //! extern crate libc;
72 //!
73 //! use std::mem;
74 //!
75 //! fn main() {
76 //!     unsafe {
77 //!         let my_num: *mut int = libc::malloc(mem::size_of::<int>() as libc::size_t) as *mut int;
78 //!         if my_num.is_null() {
79 //!             panic!("failed to allocate memory");
80 //!         }
81 //!         libc::free(my_num as *mut libc::c_void);
82 //!     }
83 //! }
84 //! ```
85 //!
86 //! Usually you wouldn't literally use `malloc` and `free` from Rust,
87 //! but C APIs hand out a lot of pointers generally, so are a common source
88 //! of unsafe pointers in Rust.
89
90 #![stable]
91
92 use mem;
93 use clone::Clone;
94 use intrinsics;
95 use option::Option::{self, Some, None};
96 use marker::{Send, Sized, Sync};
97
98 use cmp::{PartialEq, Eq, Ord, PartialOrd};
99 use cmp::Ordering::{self, Less, Equal, Greater};
100
101 // FIXME #19649: intrinsic docs don't render, so these have no docs :(
102
103 #[unstable]
104 pub use intrinsics::copy_nonoverlapping_memory;
105
106 #[unstable]
107 pub use intrinsics::copy_memory;
108
109 #[unstable = "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 int = ptr::null();
121 /// assert!(p.is_null());
122 /// ```
123 #[inline]
124 #[stable]
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 int = ptr::null_mut();
135 /// assert!(p.is_null());
136 /// ```
137 #[inline]
138 #[stable]
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 = "may play a larger role in std::ptr future extensions"]
150 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
151     set_memory(dst, 0, count);
152 }
153
154 /// Swaps the values at two mutable locations of the same type, without
155 /// deinitialising either. They may overlap, unlike `mem::swap` which is
156 /// otherwise equivalent.
157 ///
158 /// # Safety
159 ///
160 /// This is only unsafe because it accepts a raw pointer.
161 #[inline]
162 #[stable]
163 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
164     // Give ourselves some scratch space to work with
165     let mut tmp: T = mem::uninitialized();
166     let t: *mut T = &mut tmp;
167
168     // Perform the swap
169     copy_nonoverlapping_memory(t, &*x, 1);
170     copy_memory(x, &*y, 1); // `x` and `y` may overlap
171     copy_nonoverlapping_memory(y, &*t, 1);
172
173     // y and t now point to the same thing, but we need to completely forget `tmp`
174     // because it's no longer relevant.
175     mem::forget(tmp);
176 }
177
178 /// Replaces the value at `dest` with `src`, returning the old
179 /// value, without dropping either.
180 ///
181 /// # Safety
182 ///
183 /// This is only unsafe because it accepts a raw pointer.
184 /// Otherwise, this operation is identical to `mem::replace`.
185 #[inline]
186 #[stable]
187 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
188     mem::swap(mem::transmute(dest), &mut src); // cannot overlap
189     src
190 }
191
192 /// Reads the value from `src` without dropping it. This leaves the
193 /// memory in `src` unchanged.
194 ///
195 /// # Safety
196 ///
197 /// Beyond accepting a raw pointer, this is unsafe because it semantically
198 /// moves the value out of `src` without preventing further usage of `src`.
199 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
200 /// `src` is not used before the data is overwritten again (e.g. with `write`,
201 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
202 /// because it will attempt to drop the value previously at `*src`.
203 #[inline(always)]
204 #[stable]
205 pub unsafe fn read<T>(src: *const T) -> T {
206     let mut tmp: T = mem::uninitialized();
207     copy_nonoverlapping_memory(&mut tmp, src, 1);
208     tmp
209 }
210
211 /// Reads the value from `src` and nulls it out without dropping it.
212 ///
213 /// # Safety
214 ///
215 /// This is unsafe for the same reasons that `read` is unsafe.
216 #[inline(always)]
217 #[unstable = "may play a larger role in std::ptr future extensions"]
218 pub unsafe fn read_and_zero<T>(dest: *mut T) -> T {
219     // Copy the data out from `dest`:
220     let tmp = read(&*dest);
221
222     // Now zero out `dest`:
223     zero_memory(dest, 1);
224
225     tmp
226 }
227
228 /// Overwrites a memory location with the given value without reading or
229 /// dropping the old value.
230 ///
231 /// # Safety
232 ///
233 /// Beyond accepting a raw pointer, this operation is unsafe because it does
234 /// not drop the contents of `dst`. This could leak allocations or resources,
235 /// so care must be taken not to overwrite an object that should be dropped.
236 ///
237 /// This is appropriate for initializing uninitialized memory, or overwriting
238 /// memory that has previously been `read` from.
239 #[inline]
240 #[stable]
241 pub unsafe fn write<T>(dst: *mut T, src: T) {
242     intrinsics::move_val_init(&mut *dst, src)
243 }
244
245 /// Methods on raw pointers
246 #[stable]
247 pub trait PtrExt: Sized {
248     type Target;
249
250     /// Returns true if the pointer is null.
251     #[stable]
252     fn is_null(self) -> bool;
253
254     /// Returns `None` if the pointer is null, or else returns a reference to
255     /// the value wrapped in `Some`.
256     ///
257     /// # Safety
258     ///
259     /// While this method and its mutable counterpart are useful for
260     /// null-safety, it is important to note that this is still an unsafe
261     /// operation because the returned value could be pointing to invalid
262     /// memory.
263     #[unstable = "Option is not clearly the right return type, and we may want \
264                   to tie the return lifetime to a borrow of the raw pointer"]
265     unsafe fn as_ref<'a>(&self) -> Option<&'a Self::Target>;
266
267     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
268     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
269     ///
270     /// # Safety
271     ///
272     /// The offset must be in-bounds of the object, or one-byte-past-the-end.
273     /// Otherwise `offset` invokes Undefined Behaviour, regardless of whether
274     /// the pointer is used.
275     #[stable]
276     unsafe fn offset(self, count: int) -> Self;
277 }
278
279 /// Methods on mutable raw pointers
280 #[stable]
281 pub trait MutPtrExt {
282     type Target;
283
284     /// Returns `None` if the pointer is null, or else returns a mutable
285     /// reference to the value wrapped in `Some`.
286     ///
287     /// # Safety
288     ///
289     /// As with `as_ref`, this is unsafe because it cannot verify the validity
290     /// of the returned pointer.
291     #[unstable = "Option is not clearly the right return type, and we may want \
292                   to tie the return lifetime to a borrow of the raw pointer"]
293     unsafe fn as_mut<'a>(&self) -> Option<&'a mut Self::Target>;
294 }
295
296 #[stable]
297 impl<T> PtrExt for *const T {
298     type Target = T;
299
300     #[inline]
301     #[stable]
302     fn is_null(self) -> bool { self as uint == 0 }
303
304     #[inline]
305     #[stable]
306     unsafe fn offset(self, count: int) -> *const T {
307         intrinsics::offset(self, count)
308     }
309
310     #[inline]
311     #[unstable = "return value does not necessarily convey all possible \
312                   information"]
313     unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
314         if self.is_null() {
315             None
316         } else {
317             Some(&**self)
318         }
319     }
320 }
321
322 #[stable]
323 impl<T> PtrExt for *mut T {
324     type Target = T;
325
326     #[inline]
327     #[stable]
328     fn is_null(self) -> bool { self as uint == 0 }
329
330     #[inline]
331     #[stable]
332     unsafe fn offset(self, count: int) -> *mut T {
333         intrinsics::offset(self as *const T, count) as *mut T
334     }
335
336     #[inline]
337     #[unstable = "return value does not necessarily convey all possible \
338                   information"]
339     unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
340         if self.is_null() {
341             None
342         } else {
343             Some(&**self)
344         }
345     }
346 }
347
348 #[stable]
349 impl<T> MutPtrExt for *mut T {
350     type Target = T;
351
352     #[inline]
353     #[unstable = "return value does not necessarily convey all possible \
354                   information"]
355     unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> {
356         if self.is_null() {
357             None
358         } else {
359             Some(&mut **self)
360         }
361     }
362 }
363
364 // Equality for pointers
365 #[stable]
366 impl<T> PartialEq for *const T {
367     #[inline]
368     fn eq(&self, other: &*const T) -> bool {
369         *self == *other
370     }
371     #[inline]
372     fn ne(&self, other: &*const T) -> bool { !self.eq(other) }
373 }
374
375 #[stable]
376 impl<T> Eq for *const T {}
377
378 #[stable]
379 impl<T> PartialEq for *mut T {
380     #[inline]
381     fn eq(&self, other: &*mut T) -> bool {
382         *self == *other
383     }
384     #[inline]
385     fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
386 }
387
388 #[stable]
389 impl<T> Eq for *mut T {}
390
391 #[stable]
392 impl<T> Clone for *const T {
393     #[inline]
394     fn clone(&self) -> *const T {
395         *self
396     }
397 }
398
399 #[stable]
400 impl<T> Clone for *mut T {
401     #[inline]
402     fn clone(&self) -> *mut T {
403         *self
404     }
405 }
406
407 // Equality for extern "C" fn pointers
408 mod externfnpointers {
409     use mem;
410     use cmp::PartialEq;
411
412     #[stable]
413     impl<_R> PartialEq for extern "C" fn() -> _R {
414         #[inline]
415         fn eq(&self, other: &extern "C" fn() -> _R) -> bool {
416             let self_: *const () = unsafe { mem::transmute(*self) };
417             let other_: *const () = unsafe { mem::transmute(*other) };
418             self_ == other_
419         }
420     }
421     macro_rules! fnptreq {
422         ($($p:ident),*) => {
423             #[stable]
424             impl<_R,$($p),*> PartialEq for extern "C" fn($($p),*) -> _R {
425                 #[inline]
426                 fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool {
427                     let self_: *const () = unsafe { mem::transmute(*self) };
428
429                     let other_: *const () = unsafe { mem::transmute(*other) };
430                     self_ == other_
431                 }
432             }
433         }
434     }
435     fnptreq! { A }
436     fnptreq! { A,B }
437     fnptreq! { A,B,C }
438     fnptreq! { A,B,C,D }
439     fnptreq! { A,B,C,D,E }
440 }
441
442 // Comparison for pointers
443 #[stable]
444 impl<T> Ord for *const T {
445     #[inline]
446     fn cmp(&self, other: &*const T) -> Ordering {
447         if self < other {
448             Less
449         } else if self == other {
450             Equal
451         } else {
452             Greater
453         }
454     }
455 }
456
457 #[stable]
458 impl<T> PartialOrd for *const T {
459     #[inline]
460     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
461         Some(self.cmp(other))
462     }
463
464     #[inline]
465     fn lt(&self, other: &*const T) -> bool { *self < *other }
466
467     #[inline]
468     fn le(&self, other: &*const T) -> bool { *self <= *other }
469
470     #[inline]
471     fn gt(&self, other: &*const T) -> bool { *self > *other }
472
473     #[inline]
474     fn ge(&self, other: &*const T) -> bool { *self >= *other }
475 }
476
477 #[stable]
478 impl<T> Ord for *mut T {
479     #[inline]
480     fn cmp(&self, other: &*mut T) -> Ordering {
481         if self < other {
482             Less
483         } else if self == other {
484             Equal
485         } else {
486             Greater
487         }
488     }
489 }
490
491 #[stable]
492 impl<T> PartialOrd for *mut T {
493     #[inline]
494     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
495         Some(self.cmp(other))
496     }
497
498     #[inline]
499     fn lt(&self, other: &*mut T) -> bool { *self < *other }
500
501     #[inline]
502     fn le(&self, other: &*mut T) -> bool { *self <= *other }
503
504     #[inline]
505     fn gt(&self, other: &*mut T) -> bool { *self > *other }
506
507     #[inline]
508     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
509 }
510
511 /// A wrapper around a raw `*mut T` that indicates that the possessor
512 /// of this wrapper owns the referent. This in turn implies that the
513 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a
514 /// raw `*mut T` (which conveys no particular ownership semantics).
515 /// Useful for building abstractions like `Vec<T>` or `Box<T>`, which
516 /// internally use raw pointers to manage the memory that they own.
517 #[unstable = "recently added to this module"]
518 pub struct Unique<T>(pub *mut T);
519
520 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
521 /// reference is unaliased. Note that this aliasing invariant is
522 /// unenforced by the type system; the abstraction using the
523 /// `Unique` must enforce it.
524 #[unstable = "recently added to this module"]
525 unsafe impl<T:Send> Send for Unique<T> { }
526
527 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
528 /// reference is unaliased. Note that this aliasing invariant is
529 /// unenforced by the type system; the abstraction using the
530 /// `Unique` must enforce it.
531 #[unstable = "recently added to this module"]
532 unsafe impl<T:Sync> Sync for Unique<T> { }
533
534 impl<T> Unique<T> {
535     /// Returns a null Unique.
536     #[unstable = "recently added to this module"]
537     pub fn null() -> Unique<T> {
538         Unique(null_mut())
539     }
540
541     /// Return an (unsafe) pointer into the memory owned by `self`.
542     #[unstable = "recently added to this module"]
543     pub unsafe fn offset(self, offset: int) -> *mut T {
544         self.0.offset(offset)
545     }
546 }