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