]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
Make function pointers implement traits for up to 12 parameters
[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 //! Raw, unsafe pointers, `*const T`, and `*mut T`
14 //!
15 //! *[See also the pointer primitive types](../primitive.pointer.html).*
16
17 #![stable(feature = "rust1", since = "1.0.0")]
18
19 use clone::Clone;
20 use intrinsics;
21 use ops::Deref;
22 use fmt;
23 use hash;
24 use option::Option::{self, Some, None};
25 use marker::{PhantomData, Send, Sized, Sync};
26 use mem;
27 use nonzero::NonZero;
28
29 use cmp::{PartialEq, Eq, Ord, PartialOrd};
30 use cmp::Ordering::{self, Less, Equal, Greater};
31
32 // FIXME #19649: intrinsic docs don't render, so these have no docs :(
33
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use intrinsics::copy_nonoverlapping;
36
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use intrinsics::copy;
39
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub use intrinsics::write_bytes;
42
43 /// Creates a null raw pointer.
44 ///
45 /// # Examples
46 ///
47 /// ```
48 /// use std::ptr;
49 ///
50 /// let p: *const i32 = ptr::null();
51 /// assert!(p.is_null());
52 /// ```
53 #[inline]
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub const fn null<T>() -> *const T { 0 as *const T }
56
57 /// Creates a null mutable raw pointer.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use std::ptr;
63 ///
64 /// let p: *mut i32 = ptr::null_mut();
65 /// assert!(p.is_null());
66 /// ```
67 #[inline]
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
70
71 /// Swaps the values at two mutable locations of the same type, without
72 /// deinitialising either. They may overlap, unlike `mem::swap` which is
73 /// otherwise equivalent.
74 ///
75 /// # Safety
76 ///
77 /// This is only unsafe because it accepts a raw pointer.
78 #[inline]
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
81     // Give ourselves some scratch space to work with
82     let mut tmp: T = mem::uninitialized();
83
84     // Perform the swap
85     copy_nonoverlapping(x, &mut tmp, 1);
86     copy(y, x, 1); // `x` and `y` may overlap
87     copy_nonoverlapping(&tmp, y, 1);
88
89     // y and t now point to the same thing, but we need to completely forget `tmp`
90     // because it's no longer relevant.
91     mem::forget(tmp);
92 }
93
94 /// Replaces the value at `dest` with `src`, returning the old
95 /// value, without dropping either.
96 ///
97 /// # Safety
98 ///
99 /// This is only unsafe because it accepts a raw pointer.
100 /// Otherwise, this operation is identical to `mem::replace`.
101 #[inline]
102 #[stable(feature = "rust1", since = "1.0.0")]
103 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
104     mem::swap(&mut *dest, &mut src); // cannot overlap
105     src
106 }
107
108 /// Reads the value from `src` without moving it. This leaves the
109 /// memory in `src` unchanged.
110 ///
111 /// # Safety
112 ///
113 /// Beyond accepting a raw pointer, this is unsafe because it semantically
114 /// moves the value out of `src` without preventing further usage of `src`.
115 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
116 /// `src` is not used before the data is overwritten again (e.g. with `write`,
117 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
118 /// because it will attempt to drop the value previously at `*src`.
119 #[inline(always)]
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub unsafe fn read<T>(src: *const T) -> T {
122     let mut tmp: T = mem::uninitialized();
123     copy_nonoverlapping(src, &mut tmp, 1);
124     tmp
125 }
126
127 /// Variant of read_and_zero that writes the specific drop-flag byte
128 /// (which may be more appropriate than zero).
129 #[inline(always)]
130 #[unstable(feature = "filling_drop",
131            reason = "may play a larger role in std::ptr future extensions",
132            issue = "5016")]
133 pub unsafe fn read_and_drop<T>(dest: *mut T) -> T {
134     // Copy the data out from `dest`:
135     let tmp = read(&*dest);
136
137     // Now mark `dest` as dropped:
138     write_bytes(dest, mem::POST_DROP_U8, 1);
139
140     tmp
141 }
142
143 /// Overwrites a memory location with the given value without reading or
144 /// dropping the old value.
145 ///
146 /// # Safety
147 ///
148 /// Beyond accepting a raw pointer, this operation is unsafe because it does
149 /// not drop the contents of `dst`. This could leak allocations or resources,
150 /// so care must be taken not to overwrite an object that should be dropped.
151 ///
152 /// This is appropriate for initializing uninitialized memory, or overwriting
153 /// memory that has previously been `read` from.
154 #[inline]
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub unsafe fn write<T>(dst: *mut T, src: T) {
157     intrinsics::move_val_init(&mut *dst, src)
158 }
159
160 #[stable(feature = "rust1", since = "1.0.0")]
161 #[lang = "const_ptr"]
162 impl<T: ?Sized> *const T {
163     /// Returns true if the pointer is null.
164     #[stable(feature = "rust1", since = "1.0.0")]
165     #[inline]
166     pub fn is_null(self) -> bool where T: Sized {
167         self == null()
168     }
169
170     /// Returns `None` if the pointer is null, or else returns a reference to
171     /// the value wrapped in `Some`.
172     ///
173     /// # Safety
174     ///
175     /// While this method and its mutable counterpart are useful for
176     /// null-safety, it is important to note that this is still an unsafe
177     /// operation because the returned value could be pointing to invalid
178     /// memory.
179     #[unstable(feature = "ptr_as_ref",
180                reason = "Option is not clearly the right return type, and we \
181                          may want to tie the return lifetime to a borrow of \
182                          the raw pointer",
183                issue = "27780")]
184     #[inline]
185     pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
186         if self.is_null() {
187             None
188         } else {
189             Some(&**self)
190         }
191     }
192
193     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
194     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
195     ///
196     /// # Safety
197     ///
198     /// Both the starting and resulting pointer must be either in bounds or one
199     /// byte past the end of an allocated object. If either pointer is out of
200     /// bounds or arithmetic overflow occurs then
201     /// any further use of the returned value will result in undefined behavior.
202     #[stable(feature = "rust1", since = "1.0.0")]
203     #[inline]
204     pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
205         intrinsics::offset(self, count)
206     }
207 }
208
209 #[stable(feature = "rust1", since = "1.0.0")]
210 #[lang = "mut_ptr"]
211 impl<T: ?Sized> *mut T {
212     /// Returns true if the pointer is null.
213     #[stable(feature = "rust1", since = "1.0.0")]
214     #[inline]
215     pub fn is_null(self) -> bool where T: Sized {
216         self == null_mut()
217     }
218
219     /// Returns `None` if the pointer is null, or else returns a reference to
220     /// the value wrapped in `Some`.
221     ///
222     /// # Safety
223     ///
224     /// While this method and its mutable counterpart are useful for
225     /// null-safety, it is important to note that this is still an unsafe
226     /// operation because the returned value could be pointing to invalid
227     /// memory.
228     #[unstable(feature = "ptr_as_ref",
229                reason = "Option is not clearly the right return type, and we \
230                          may want to tie the return lifetime to a borrow of \
231                          the raw pointer",
232                issue = "27780")]
233     #[inline]
234     pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
235         if self.is_null() {
236             None
237         } else {
238             Some(&**self)
239         }
240     }
241
242     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
243     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
244     ///
245     /// # Safety
246     ///
247     /// The offset must be in-bounds of the object, or one-byte-past-the-end.
248     /// Otherwise `offset` invokes Undefined Behaviour, regardless of whether
249     /// the pointer is used.
250     #[stable(feature = "rust1", since = "1.0.0")]
251     #[inline]
252     pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
253         intrinsics::offset(self, count) as *mut T
254     }
255
256     /// Returns `None` if the pointer is null, or else returns a mutable
257     /// reference to the value wrapped in `Some`.
258     ///
259     /// # Safety
260     ///
261     /// As with `as_ref`, this is unsafe because it cannot verify the validity
262     /// of the returned pointer.
263     #[unstable(feature = "ptr_as_ref",
264                reason = "return value does not necessarily convey all possible \
265                          information",
266                issue = "27780")]
267     #[inline]
268     pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> where T: Sized {
269         if self.is_null() {
270             None
271         } else {
272             Some(&mut **self)
273         }
274     }
275 }
276
277 // Equality for pointers
278 #[stable(feature = "rust1", since = "1.0.0")]
279 impl<T: ?Sized> PartialEq for *const T {
280     #[inline]
281     fn eq(&self, other: &*const T) -> bool { *self == *other }
282 }
283
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl<T: ?Sized> Eq for *const T {}
286
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<T: ?Sized> PartialEq for *mut T {
289     #[inline]
290     fn eq(&self, other: &*mut T) -> bool { *self == *other }
291 }
292
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl<T: ?Sized> Eq for *mut T {}
295
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<T: ?Sized> Clone for *const T {
298     #[inline]
299     fn clone(&self) -> *const T {
300         *self
301     }
302 }
303
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl<T: ?Sized> Clone for *mut T {
306     #[inline]
307     fn clone(&self) -> *mut T {
308         *self
309     }
310 }
311
312 // Impls for function pointers
313 macro_rules! fnptr_impls_safety_abi {
314     ($FnTy: ty, $($Arg: ident),*) => {
315         #[stable(feature = "rust1", since = "1.0.0")]
316         impl<Ret, $($Arg),*> Clone for $FnTy {
317             #[inline]
318             fn clone(&self) -> Self {
319                 *self
320             }
321         }
322
323         #[stable(feature = "fnptr_impls", since = "1.4.0")]
324         impl<Ret, $($Arg),*> PartialEq for $FnTy {
325             #[inline]
326             fn eq(&self, other: &Self) -> bool {
327                 *self as usize == *other as usize
328             }
329         }
330
331         #[stable(feature = "fnptr_impls", since = "1.4.0")]
332         impl<Ret, $($Arg),*> Eq for $FnTy {}
333
334         #[stable(feature = "fnptr_impls", since = "1.4.0")]
335         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
336             #[inline]
337             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
338                 (*self as usize).partial_cmp(&(*other as usize))
339             }
340         }
341
342         #[stable(feature = "fnptr_impls", since = "1.4.0")]
343         impl<Ret, $($Arg),*> Ord for $FnTy {
344             #[inline]
345             fn cmp(&self, other: &Self) -> Ordering {
346                 (*self as usize).cmp(&(*other as usize))
347             }
348         }
349
350         #[stable(feature = "fnptr_impls", since = "1.4.0")]
351         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
352             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
353                 state.write_usize(*self as usize)
354             }
355         }
356
357         #[stable(feature = "fnptr_impls", since = "1.4.0")]
358         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
359             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
360                 fmt::Pointer::fmt(&(*self as *const ()), f)
361             }
362         }
363
364         #[stable(feature = "fnptr_impls", since = "1.4.0")]
365         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
366             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
367                 fmt::Pointer::fmt(&(*self as *const ()), f)
368             }
369         }
370     }
371 }
372
373 macro_rules! fnptr_impls_args {
374     ($($Arg: ident),*) => {
375         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
376         fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
377         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
378         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
379     }
380 }
381
382 fnptr_impls_args! { }
383 fnptr_impls_args! { A }
384 fnptr_impls_args! { A, B }
385 fnptr_impls_args! { A, B, C }
386 fnptr_impls_args! { A, B, C, D }
387 fnptr_impls_args! { A, B, C, D, E }
388 fnptr_impls_args! { A, B, C, D, E, F }
389 fnptr_impls_args! { A, B, C, D, E, F, G }
390 fnptr_impls_args! { A, B, C, D, E, F, G, H }
391 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
392 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
393 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
394 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
395
396 // Comparison for pointers
397 #[stable(feature = "rust1", since = "1.0.0")]
398 impl<T: ?Sized> Ord for *const T {
399     #[inline]
400     fn cmp(&self, other: &*const T) -> Ordering {
401         if self < other {
402             Less
403         } else if self == other {
404             Equal
405         } else {
406             Greater
407         }
408     }
409 }
410
411 #[stable(feature = "rust1", since = "1.0.0")]
412 impl<T: ?Sized> PartialOrd for *const T {
413     #[inline]
414     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
415         Some(self.cmp(other))
416     }
417
418     #[inline]
419     fn lt(&self, other: &*const T) -> bool { *self < *other }
420
421     #[inline]
422     fn le(&self, other: &*const T) -> bool { *self <= *other }
423
424     #[inline]
425     fn gt(&self, other: &*const T) -> bool { *self > *other }
426
427     #[inline]
428     fn ge(&self, other: &*const T) -> bool { *self >= *other }
429 }
430
431 #[stable(feature = "rust1", since = "1.0.0")]
432 impl<T: ?Sized> Ord for *mut T {
433     #[inline]
434     fn cmp(&self, other: &*mut T) -> Ordering {
435         if self < other {
436             Less
437         } else if self == other {
438             Equal
439         } else {
440             Greater
441         }
442     }
443 }
444
445 #[stable(feature = "rust1", since = "1.0.0")]
446 impl<T: ?Sized> PartialOrd for *mut T {
447     #[inline]
448     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
449         Some(self.cmp(other))
450     }
451
452     #[inline]
453     fn lt(&self, other: &*mut T) -> bool { *self < *other }
454
455     #[inline]
456     fn le(&self, other: &*mut T) -> bool { *self <= *other }
457
458     #[inline]
459     fn gt(&self, other: &*mut T) -> bool { *self > *other }
460
461     #[inline]
462     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
463 }
464
465 /// A wrapper around a raw `*mut T` that indicates that the possessor
466 /// of this wrapper owns the referent. This in turn implies that the
467 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
468 /// `*mut T` (which conveys no particular ownership semantics).  It
469 /// also implies that the referent of the pointer should not be
470 /// modified without a unique path to the `Unique` reference. Useful
471 /// for building abstractions like `Vec<T>` or `Box<T>`, which
472 /// internally use raw pointers to manage the memory that they own.
473 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
474            issue = "27730")]
475 pub struct Unique<T: ?Sized> {
476     pointer: NonZero<*const T>,
477     // NOTE: this marker has no consequences for variance, but is necessary
478     // for dropck to understand that we logically own a `T`.
479     //
480     // For details, see:
481     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
482     _marker: PhantomData<T>,
483 }
484
485 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
486 /// reference is unaliased. Note that this aliasing invariant is
487 /// unenforced by the type system; the abstraction using the
488 /// `Unique` must enforce it.
489 #[unstable(feature = "unique", issue = "27730")]
490 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
491
492 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
493 /// reference is unaliased. Note that this aliasing invariant is
494 /// unenforced by the type system; the abstraction using the
495 /// `Unique` must enforce it.
496 #[unstable(feature = "unique", issue = "27730")]
497 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
498
499 #[unstable(feature = "unique", issue = "27730")]
500 impl<T: ?Sized> Unique<T> {
501     /// Creates a new `Unique`.
502     pub unsafe fn new(ptr: *mut T) -> Unique<T> {
503         Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
504     }
505
506     /// Dereferences the content.
507     pub unsafe fn get(&self) -> &T {
508         &**self.pointer
509     }
510
511     /// Mutably dereferences the content.
512     pub unsafe fn get_mut(&mut self) -> &mut T {
513         &mut ***self
514     }
515 }
516
517 #[unstable(feature = "unique", issue= "27730")]
518 impl<T:?Sized> Deref for Unique<T> {
519     type Target = *mut T;
520
521     #[inline]
522     fn deref(&self) -> &*mut T {
523         unsafe { mem::transmute(&*self.pointer) }
524     }
525 }
526
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl<T> fmt::Pointer for Unique<T> {
529     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
530         fmt::Pointer::fmt(&*self.pointer, f)
531     }
532 }