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