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