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