]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
Mention in the docs, that `assert!` has a second version with a custom message
[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::{CoerceUnsized, Deref};
22 use fmt;
23 use hash;
24 use option::Option::{self, Some, None};
25 use marker::{Copy, PhantomData, Send, Sized, Sync, Unsize};
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 /// deinitializing 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 /// This operation is marked unsafe because it accepts a raw pointer.
149 ///
150 /// It does not drop the contents of `dst`. This is safe, but it could leak
151 /// allocations or resources, so care must be taken not to overwrite an object
152 /// that should be dropped.
153 ///
154 /// This is appropriate for initializing uninitialized memory, or overwriting
155 /// memory that has previously been `read` from.
156 #[inline]
157 #[stable(feature = "rust1", since = "1.0.0")]
158 pub unsafe fn write<T>(dst: *mut T, src: T) {
159     intrinsics::move_val_init(&mut *dst, src)
160 }
161
162 #[stable(feature = "rust1", since = "1.0.0")]
163 #[lang = "const_ptr"]
164 impl<T: ?Sized> *const T {
165     /// Returns true if the pointer is null.
166     #[stable(feature = "rust1", since = "1.0.0")]
167     #[inline]
168     pub fn is_null(self) -> bool where T: Sized {
169         self == null()
170     }
171
172     /// Returns `None` if the pointer is null, or else returns a reference to
173     /// the value wrapped in `Some`.
174     ///
175     /// # Safety
176     ///
177     /// While this method and its mutable counterpart are useful for
178     /// null-safety, it is important to note that this is still an unsafe
179     /// operation because the returned value could be pointing to invalid
180     /// memory.
181     #[unstable(feature = "ptr_as_ref",
182                reason = "Option is not clearly the right return type, and we \
183                          may want to tie the return lifetime to a borrow of \
184                          the raw pointer",
185                issue = "27780")]
186     #[inline]
187     pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
188         if self.is_null() {
189             None
190         } else {
191             Some(&**self)
192         }
193     }
194
195     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
196     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
197     ///
198     /// # Safety
199     ///
200     /// Both the starting and resulting pointer must be either in bounds or one
201     /// byte past the end of an allocated object. If either pointer is out of
202     /// bounds or arithmetic overflow occurs then
203     /// any further use of the returned value will result in undefined behavior.
204     #[stable(feature = "rust1", since = "1.0.0")]
205     #[inline]
206     pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
207         intrinsics::offset(self, count)
208     }
209 }
210
211 #[stable(feature = "rust1", since = "1.0.0")]
212 #[lang = "mut_ptr"]
213 impl<T: ?Sized> *mut T {
214     /// Returns true if the pointer is null.
215     #[stable(feature = "rust1", since = "1.0.0")]
216     #[inline]
217     pub fn is_null(self) -> bool where T: Sized {
218         self == null_mut()
219     }
220
221     /// Returns `None` if the pointer is null, or else returns a reference to
222     /// the value wrapped in `Some`.
223     ///
224     /// # Safety
225     ///
226     /// While this method and its mutable counterpart are useful for
227     /// null-safety, it is important to note that this is still an unsafe
228     /// operation because the returned value could be pointing to invalid
229     /// memory.
230     #[unstable(feature = "ptr_as_ref",
231                reason = "Option is not clearly the right return type, and we \
232                          may want to tie the return lifetime to a borrow of \
233                          the raw pointer",
234                issue = "27780")]
235     #[inline]
236     pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
237         if self.is_null() {
238             None
239         } else {
240             Some(&**self)
241         }
242     }
243
244     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
245     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
246     ///
247     /// # Safety
248     ///
249     /// The offset must be in-bounds of the object, or one-byte-past-the-end.
250     /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
251     /// the pointer is used.
252     #[stable(feature = "rust1", since = "1.0.0")]
253     #[inline]
254     pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
255         intrinsics::offset(self, count) as *mut T
256     }
257
258     /// Returns `None` if the pointer is null, or else returns a mutable
259     /// reference to the value wrapped in `Some`.
260     ///
261     /// # Safety
262     ///
263     /// As with `as_ref`, this is unsafe because it cannot verify the validity
264     /// of the returned pointer.
265     #[unstable(feature = "ptr_as_ref",
266                reason = "return value does not necessarily convey all possible \
267                          information",
268                issue = "27780")]
269     #[inline]
270     pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> where T: Sized {
271         if self.is_null() {
272             None
273         } else {
274             Some(&mut **self)
275         }
276     }
277 }
278
279 // Equality for pointers
280 #[stable(feature = "rust1", since = "1.0.0")]
281 impl<T: ?Sized> PartialEq for *const T {
282     #[inline]
283     fn eq(&self, other: &*const T) -> bool { *self == *other }
284 }
285
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl<T: ?Sized> Eq for *const T {}
288
289 #[stable(feature = "rust1", since = "1.0.0")]
290 impl<T: ?Sized> PartialEq for *mut T {
291     #[inline]
292     fn eq(&self, other: &*mut T) -> bool { *self == *other }
293 }
294
295 #[stable(feature = "rust1", since = "1.0.0")]
296 impl<T: ?Sized> Eq for *mut T {}
297
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl<T: ?Sized> Clone for *const T {
300     #[inline]
301     fn clone(&self) -> *const T {
302         *self
303     }
304 }
305
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<T: ?Sized> Clone for *mut T {
308     #[inline]
309     fn clone(&self) -> *mut T {
310         *self
311     }
312 }
313
314 // Impls for function pointers
315 macro_rules! fnptr_impls_safety_abi {
316     ($FnTy: ty, $($Arg: ident),*) => {
317         #[stable(feature = "rust1", since = "1.0.0")]
318         impl<Ret, $($Arg),*> Clone for $FnTy {
319             #[inline]
320             fn clone(&self) -> Self {
321                 *self
322             }
323         }
324
325         #[stable(feature = "fnptr_impls", since = "1.4.0")]
326         impl<Ret, $($Arg),*> PartialEq for $FnTy {
327             #[inline]
328             fn eq(&self, other: &Self) -> bool {
329                 *self as usize == *other as usize
330             }
331         }
332
333         #[stable(feature = "fnptr_impls", since = "1.4.0")]
334         impl<Ret, $($Arg),*> Eq for $FnTy {}
335
336         #[stable(feature = "fnptr_impls", since = "1.4.0")]
337         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
338             #[inline]
339             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
340                 (*self as usize).partial_cmp(&(*other as usize))
341             }
342         }
343
344         #[stable(feature = "fnptr_impls", since = "1.4.0")]
345         impl<Ret, $($Arg),*> Ord for $FnTy {
346             #[inline]
347             fn cmp(&self, other: &Self) -> Ordering {
348                 (*self as usize).cmp(&(*other as usize))
349             }
350         }
351
352         #[stable(feature = "fnptr_impls", since = "1.4.0")]
353         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
354             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
355                 state.write_usize(*self as usize)
356             }
357         }
358
359         #[stable(feature = "fnptr_impls", since = "1.4.0")]
360         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
361             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
362                 fmt::Pointer::fmt(&(*self as *const ()), f)
363             }
364         }
365
366         #[stable(feature = "fnptr_impls", since = "1.4.0")]
367         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
368             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
369                 fmt::Pointer::fmt(&(*self as *const ()), f)
370             }
371         }
372     }
373 }
374
375 macro_rules! fnptr_impls_args {
376     ($($Arg: ident),*) => {
377         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
378         fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
379         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
380         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
381     }
382 }
383
384 fnptr_impls_args! { }
385 fnptr_impls_args! { A }
386 fnptr_impls_args! { A, B }
387 fnptr_impls_args! { A, B, C }
388 fnptr_impls_args! { A, B, C, D }
389 fnptr_impls_args! { A, B, C, D, E }
390 fnptr_impls_args! { A, B, C, D, E, F }
391 fnptr_impls_args! { A, B, C, D, E, F, G }
392 fnptr_impls_args! { A, B, C, D, E, F, G, H }
393 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
394 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
395 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
396 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
397
398 // Comparison for pointers
399 #[stable(feature = "rust1", since = "1.0.0")]
400 impl<T: ?Sized> Ord for *const T {
401     #[inline]
402     fn cmp(&self, other: &*const T) -> Ordering {
403         if self < other {
404             Less
405         } else if self == other {
406             Equal
407         } else {
408             Greater
409         }
410     }
411 }
412
413 #[stable(feature = "rust1", since = "1.0.0")]
414 impl<T: ?Sized> PartialOrd for *const T {
415     #[inline]
416     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
417         Some(self.cmp(other))
418     }
419
420     #[inline]
421     fn lt(&self, other: &*const T) -> bool { *self < *other }
422
423     #[inline]
424     fn le(&self, other: &*const T) -> bool { *self <= *other }
425
426     #[inline]
427     fn gt(&self, other: &*const T) -> bool { *self > *other }
428
429     #[inline]
430     fn ge(&self, other: &*const T) -> bool { *self >= *other }
431 }
432
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl<T: ?Sized> Ord for *mut T {
435     #[inline]
436     fn cmp(&self, other: &*mut T) -> Ordering {
437         if self < other {
438             Less
439         } else if self == other {
440             Equal
441         } else {
442             Greater
443         }
444     }
445 }
446
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl<T: ?Sized> PartialOrd for *mut T {
449     #[inline]
450     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
451         Some(self.cmp(other))
452     }
453
454     #[inline]
455     fn lt(&self, other: &*mut T) -> bool { *self < *other }
456
457     #[inline]
458     fn le(&self, other: &*mut T) -> bool { *self <= *other }
459
460     #[inline]
461     fn gt(&self, other: &*mut T) -> bool { *self > *other }
462
463     #[inline]
464     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
465 }
466
467 /// A wrapper around a raw `*mut T` that indicates that the possessor
468 /// of this wrapper owns the referent. This in turn implies that the
469 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
470 /// `*mut T` (which conveys no particular ownership semantics).  It
471 /// also implies that the referent of the pointer should not be
472 /// modified without a unique path to the `Unique` reference. Useful
473 /// for building abstractions like `Vec<T>` or `Box<T>`, which
474 /// internally use raw pointers to manage the memory that they own.
475 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
476            issue = "27730")]
477 pub struct Unique<T: ?Sized> {
478     pointer: NonZero<*const T>,
479     // NOTE: this marker has no consequences for variance, but is necessary
480     // for dropck to understand that we logically own a `T`.
481     //
482     // For details, see:
483     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
484     _marker: PhantomData<T>,
485 }
486
487 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
488 /// reference is unaliased. Note that this aliasing invariant is
489 /// unenforced by the type system; the abstraction using the
490 /// `Unique` must enforce it.
491 #[unstable(feature = "unique", issue = "27730")]
492 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
493
494 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
495 /// reference is unaliased. Note that this aliasing invariant is
496 /// unenforced by the type system; the abstraction using the
497 /// `Unique` must enforce it.
498 #[unstable(feature = "unique", issue = "27730")]
499 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
500
501 #[cfg(stage0)]
502 macro_rules! unique_new {
503     () => (
504         /// Creates a new `Unique`.
505         pub unsafe fn new(ptr: *mut T) -> Unique<T> {
506             Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
507         }
508     )
509 }
510 #[cfg(not(stage0))]
511 macro_rules! unique_new {
512     () => (
513         /// Creates a new `Unique`.
514         pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
515             Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
516         }
517     )
518 }
519
520 #[unstable(feature = "unique", issue = "27730")]
521 impl<T: ?Sized> Unique<T> {
522     unique_new!{}
523
524     /// Dereferences the content.
525     pub unsafe fn get(&self) -> &T {
526         &**self.pointer
527     }
528
529     /// Mutably dereferences the content.
530     pub unsafe fn get_mut(&mut self) -> &mut T {
531         &mut ***self
532     }
533 }
534
535 #[unstable(feature = "unique", issue= "27730")]
536 impl<T:?Sized> Deref for Unique<T> {
537     type Target = *mut T;
538
539     #[inline]
540     fn deref(&self) -> &*mut T {
541         unsafe { mem::transmute(&*self.pointer) }
542     }
543 }
544
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl<T> fmt::Pointer for Unique<T> {
547     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
548         fmt::Pointer::fmt(&*self.pointer, f)
549     }
550 }
551
552 /// A wrapper around a raw `*mut T` that indicates that the possessor
553 /// of this wrapper has shared ownership of the referent. Useful for
554 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
555 /// use raw pointers to manage the memory that they own.
556 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
557            issue = "27730")]
558 pub struct Shared<T: ?Sized> {
559     pointer: NonZero<*const T>,
560     // NOTE: this marker has no consequences for variance, but is necessary
561     // for dropck to understand that we logically own a `T`.
562     //
563     // For details, see:
564     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
565     _marker: PhantomData<T>,
566 }
567
568 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
569 // NB: This impl is unnecessary, but should provide better error messages.
570 #[unstable(feature = "shared", issue = "27730")]
571 impl<T: ?Sized> !Send for Shared<T> { }
572
573 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
574 // NB: This impl is unnecessary, but should provide better error messages.
575 #[unstable(feature = "shared", issue = "27730")]
576 impl<T: ?Sized> !Sync for Shared<T> { }
577
578 #[unstable(feature = "shared", issue = "27730")]
579 impl<T: ?Sized> Shared<T> {
580     /// Creates a new `Shared`.
581     pub unsafe fn new(ptr: *mut T) -> Self {
582         Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
583     }
584 }
585
586 #[unstable(feature = "shared", issue = "27730")]
587 impl<T: ?Sized> Clone for Shared<T> {
588     fn clone(&self) -> Self {
589         *self
590     }
591 }
592
593 #[unstable(feature = "shared", issue = "27730")]
594 impl<T: ?Sized> Copy for Shared<T> { }
595
596 #[cfg(not(stage0))] // remove cfg after new snapshot
597 #[unstable(feature = "shared", issue = "27730")]
598 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
599
600 #[unstable(feature = "shared", issue = "27730")]
601 impl<T: ?Sized> Deref for Shared<T> {
602     type Target = *mut T;
603
604     #[inline]
605     fn deref(&self) -> &*mut T {
606         unsafe { mem::transmute(&*self.pointer) }
607     }
608 }
609
610 #[unstable(feature = "shared", issue = "27730")]
611 impl<T> fmt::Pointer for Shared<T> {
612     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
613         fmt::Pointer::fmt(&*self.pointer, f)
614     }
615 }