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