]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
Rollup merge of #35867 - frewsxcv:rustdoc-cleanup, 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](../../std/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 #[stable(feature = "drop_in_place", since = "1.8.0")]
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 ///
123 /// # Examples
124 ///
125 /// Basic usage:
126 ///
127 /// ```
128 /// let x = 12;
129 /// let y = &x as *const i32;
130 ///
131 /// unsafe {
132 ///     assert_eq!(std::ptr::read(y), 12);
133 /// }
134 /// ```
135 #[inline(always)]
136 #[stable(feature = "rust1", since = "1.0.0")]
137 pub unsafe fn read<T>(src: *const T) -> T {
138     let mut tmp: T = mem::uninitialized();
139     copy_nonoverlapping(src, &mut tmp, 1);
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 ///
157 /// # Examples
158 ///
159 /// Basic usage:
160 ///
161 /// ```
162 /// let mut x = 0;
163 /// let y = &mut x as *mut i32;
164 /// let z = 12;
165 ///
166 /// unsafe {
167 ///     std::ptr::write(y, z);
168 ///     assert_eq!(std::ptr::read(y), 12);
169 /// }
170 /// ```
171 #[inline]
172 #[stable(feature = "rust1", since = "1.0.0")]
173 pub unsafe fn write<T>(dst: *mut T, src: T) {
174     intrinsics::move_val_init(&mut *dst, src)
175 }
176
177 /// Performs a volatile read of the value from `src` without moving it. This
178 /// leaves the memory in `src` unchanged.
179 ///
180 /// Volatile operations are intended to act on I/O memory, and are guaranteed
181 /// to not be elided or reordered by the compiler across other volatile
182 /// operations.
183 ///
184 /// # Notes
185 ///
186 /// Rust does not currently have a rigorously and formally defined memory model,
187 /// so the precise semantics of what "volatile" means here is subject to change
188 /// over time. That being said, the semantics will almost always end up pretty
189 /// similar to [C11's definition of volatile][c11].
190 ///
191 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
192 ///
193 /// # Safety
194 ///
195 /// Beyond accepting a raw pointer, this is unsafe because it semantically
196 /// moves the value out of `src` without preventing further usage of `src`.
197 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
198 /// `src` is not used before the data is overwritten again (e.g. with `write`,
199 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
200 /// because it will attempt to drop the value previously at `*src`.
201 ///
202 /// # Examples
203 ///
204 /// Basic usage:
205 ///
206 /// ```
207 /// let x = 12;
208 /// let y = &x as *const i32;
209 ///
210 /// unsafe {
211 ///     assert_eq!(std::ptr::read_volatile(y), 12);
212 /// }
213 /// ```
214 #[inline]
215 #[stable(feature = "volatile", since = "1.9.0")]
216 pub unsafe fn read_volatile<T>(src: *const T) -> T {
217     intrinsics::volatile_load(src)
218 }
219
220 /// Performs a volatile write of a memory location with the given value without
221 /// reading or dropping the old value.
222 ///
223 /// Volatile operations are intended to act on I/O memory, and are guaranteed
224 /// to not be elided or reordered by the compiler across other volatile
225 /// operations.
226 ///
227 /// # Notes
228 ///
229 /// Rust does not currently have a rigorously and formally defined memory model,
230 /// so the precise semantics of what "volatile" means here is subject to change
231 /// over time. That being said, the semantics will almost always end up pretty
232 /// similar to [C11's definition of volatile][c11].
233 ///
234 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
235 ///
236 /// # Safety
237 ///
238 /// This operation is marked unsafe because it accepts a raw pointer.
239 ///
240 /// It does not drop the contents of `dst`. This is safe, but it could leak
241 /// allocations or resources, so care must be taken not to overwrite an object
242 /// that should be dropped.
243 ///
244 /// This is appropriate for initializing uninitialized memory, or overwriting
245 /// memory that has previously been `read` from.
246 ///
247 /// # Examples
248 ///
249 /// Basic usage:
250 ///
251 /// ```
252 /// let mut x = 0;
253 /// let y = &mut x as *mut i32;
254 /// let z = 12;
255 ///
256 /// unsafe {
257 ///     std::ptr::write_volatile(y, z);
258 ///     assert_eq!(std::ptr::read_volatile(y), 12);
259 /// }
260 /// ```
261 #[inline]
262 #[stable(feature = "volatile", since = "1.9.0")]
263 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
264     intrinsics::volatile_store(dst, src);
265 }
266
267 #[lang = "const_ptr"]
268 impl<T: ?Sized> *const T {
269     /// Returns true if the pointer is null.
270     ///
271     /// # Examples
272     ///
273     /// Basic usage:
274     ///
275     /// ```
276     /// let s: &str = "Follow the rabbit";
277     /// let ptr: *const u8 = s.as_ptr();
278     /// assert!(!ptr.is_null());
279     /// ```
280     #[stable(feature = "rust1", since = "1.0.0")]
281     #[inline]
282     pub fn is_null(self) -> bool where T: Sized {
283         self == null()
284     }
285
286     /// Returns `None` if the pointer is null, or else returns a reference to
287     /// the value wrapped in `Some`.
288     ///
289     /// # Safety
290     ///
291     /// While this method and its mutable counterpart are useful for
292     /// null-safety, it is important to note that this is still an unsafe
293     /// operation because the returned value could be pointing to invalid
294     /// memory.
295     ///
296     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
297     /// not necessarily reflect the actual lifetime of the data.
298     ///
299     /// # Examples
300     ///
301     /// Basic usage:
302     ///
303     /// ```ignore
304     /// let val: *const u8 = &10u8 as *const u8;
305     ///
306     /// unsafe {
307     ///     if let Some(val_back) = val.as_ref() {
308     ///         println!("We got back the value: {}!", val_back);
309     ///     }
310     /// }
311     /// ```
312     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
313     #[inline]
314     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
315         if self.is_null() {
316             None
317         } else {
318             Some(&*self)
319         }
320     }
321
322     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
323     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
324     ///
325     /// # Safety
326     ///
327     /// Both the starting and resulting pointer must be either in bounds or one
328     /// byte past the end of an allocated object. If either pointer is out of
329     /// bounds or arithmetic overflow occurs then
330     /// any further use of the returned value will result in undefined behavior.
331     ///
332     /// # Examples
333     ///
334     /// Basic usage:
335     ///
336     /// ```
337     /// let s: &str = "123";
338     /// let ptr: *const u8 = s.as_ptr();
339     ///
340     /// unsafe {
341     ///     println!("{}", *ptr.offset(1) as char);
342     ///     println!("{}", *ptr.offset(2) as char);
343     /// }
344     /// ```
345     #[stable(feature = "rust1", since = "1.0.0")]
346     #[inline]
347     pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
348         intrinsics::offset(self, count)
349     }
350 }
351
352 #[lang = "mut_ptr"]
353 impl<T: ?Sized> *mut T {
354     /// Returns true if the pointer is null.
355     ///
356     /// # Examples
357     ///
358     /// Basic usage:
359     ///
360     /// ```
361     /// let mut s = [1, 2, 3];
362     /// let ptr: *mut u32 = s.as_mut_ptr();
363     /// assert!(!ptr.is_null());
364     /// ```
365     #[stable(feature = "rust1", since = "1.0.0")]
366     #[inline]
367     pub fn is_null(self) -> bool where T: Sized {
368         self == null_mut()
369     }
370
371     /// Returns `None` if the pointer is null, or else returns a reference to
372     /// the value wrapped in `Some`.
373     ///
374     /// # Safety
375     ///
376     /// While this method and its mutable counterpart are useful for
377     /// null-safety, it is important to note that this is still an unsafe
378     /// operation because the returned value could be pointing to invalid
379     /// memory.
380     ///
381     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
382     /// not necessarily reflect the actual lifetime of the data.
383     ///
384     /// # Examples
385     ///
386     /// Basic usage:
387     ///
388     /// ```ignore
389     /// let val: *mut u8 = &mut 10u8 as *mut u8;
390     ///
391     /// unsafe {
392     ///     if let Some(val_back) = val.as_ref() {
393     ///         println!("We got back the value: {}!", val_back);
394     ///     }
395     /// }
396     /// ```
397     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
398     #[inline]
399     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
400         if self.is_null() {
401             None
402         } else {
403             Some(&*self)
404         }
405     }
406
407     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
408     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
409     ///
410     /// # Safety
411     ///
412     /// The offset must be in-bounds of the object, or one-byte-past-the-end.
413     /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
414     /// the pointer is used.
415     ///
416     /// # Examples
417     ///
418     /// Basic usage:
419     ///
420     /// ```
421     /// let mut s = [1, 2, 3];
422     /// let ptr: *mut u32 = s.as_mut_ptr();
423     ///
424     /// unsafe {
425     ///     println!("{}", *ptr.offset(1));
426     ///     println!("{}", *ptr.offset(2));
427     /// }
428     /// ```
429     #[stable(feature = "rust1", since = "1.0.0")]
430     #[inline]
431     pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
432         intrinsics::offset(self, count) as *mut T
433     }
434
435     /// Returns `None` if the pointer is null, or else returns a mutable
436     /// reference to the value wrapped in `Some`.
437     ///
438     /// # Safety
439     ///
440     /// As with `as_ref`, this is unsafe because it cannot verify the validity
441     /// of the returned pointer, nor can it ensure that the lifetime `'a`
442     /// returned is indeed a valid lifetime for the contained data.
443     ///
444     /// # Examples
445     ///
446     /// Basic usage:
447     ///
448     /// ```
449     /// let mut s = [1, 2, 3];
450     /// let ptr: *mut u32 = s.as_mut_ptr();
451     /// let first_value = unsafe { ptr.as_mut().unwrap() };
452     /// *first_value = 4;
453     /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
454     /// ```
455     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
456     #[inline]
457     pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
458         if self.is_null() {
459             None
460         } else {
461             Some(&mut *self)
462         }
463     }
464 }
465
466 // Equality for pointers
467 #[stable(feature = "rust1", since = "1.0.0")]
468 impl<T: ?Sized> PartialEq for *const T {
469     #[inline]
470     fn eq(&self, other: &*const T) -> bool { *self == *other }
471 }
472
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl<T: ?Sized> Eq for *const T {}
475
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl<T: ?Sized> PartialEq for *mut T {
478     #[inline]
479     fn eq(&self, other: &*mut T) -> bool { *self == *other }
480 }
481
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl<T: ?Sized> Eq for *mut T {}
484
485 #[stable(feature = "rust1", since = "1.0.0")]
486 impl<T: ?Sized> Clone for *const T {
487     #[inline]
488     fn clone(&self) -> *const T {
489         *self
490     }
491 }
492
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl<T: ?Sized> Clone for *mut T {
495     #[inline]
496     fn clone(&self) -> *mut T {
497         *self
498     }
499 }
500
501 // Impls for function pointers
502 macro_rules! fnptr_impls_safety_abi {
503     ($FnTy: ty, $($Arg: ident),*) => {
504         #[stable(feature = "rust1", since = "1.0.0")]
505         impl<Ret, $($Arg),*> Clone for $FnTy {
506             #[inline]
507             fn clone(&self) -> Self {
508                 *self
509             }
510         }
511
512         #[stable(feature = "fnptr_impls", since = "1.4.0")]
513         impl<Ret, $($Arg),*> PartialEq for $FnTy {
514             #[inline]
515             fn eq(&self, other: &Self) -> bool {
516                 *self as usize == *other as usize
517             }
518         }
519
520         #[stable(feature = "fnptr_impls", since = "1.4.0")]
521         impl<Ret, $($Arg),*> Eq for $FnTy {}
522
523         #[stable(feature = "fnptr_impls", since = "1.4.0")]
524         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
525             #[inline]
526             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
527                 (*self as usize).partial_cmp(&(*other as usize))
528             }
529         }
530
531         #[stable(feature = "fnptr_impls", since = "1.4.0")]
532         impl<Ret, $($Arg),*> Ord for $FnTy {
533             #[inline]
534             fn cmp(&self, other: &Self) -> Ordering {
535                 (*self as usize).cmp(&(*other as usize))
536             }
537         }
538
539         #[stable(feature = "fnptr_impls", since = "1.4.0")]
540         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
541             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
542                 state.write_usize(*self as usize)
543             }
544         }
545
546         #[stable(feature = "fnptr_impls", since = "1.4.0")]
547         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
548             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549                 fmt::Pointer::fmt(&(*self as *const ()), f)
550             }
551         }
552
553         #[stable(feature = "fnptr_impls", since = "1.4.0")]
554         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
555             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
556                 fmt::Pointer::fmt(&(*self as *const ()), f)
557             }
558         }
559     }
560 }
561
562 macro_rules! fnptr_impls_args {
563     ($($Arg: ident),+) => {
564         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
565         fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
566         fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
567         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
568         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
569         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
570     };
571     () => {
572         // No variadic functions with 0 parameters
573         fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
574         fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
575         fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
576         fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
577     };
578 }
579
580 fnptr_impls_args! { }
581 fnptr_impls_args! { A }
582 fnptr_impls_args! { A, B }
583 fnptr_impls_args! { A, B, C }
584 fnptr_impls_args! { A, B, C, D }
585 fnptr_impls_args! { A, B, C, D, E }
586 fnptr_impls_args! { A, B, C, D, E, F }
587 fnptr_impls_args! { A, B, C, D, E, F, G }
588 fnptr_impls_args! { A, B, C, D, E, F, G, H }
589 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
590 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
591 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
592 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
593
594 // Comparison for pointers
595 #[stable(feature = "rust1", since = "1.0.0")]
596 impl<T: ?Sized> Ord for *const T {
597     #[inline]
598     fn cmp(&self, other: &*const T) -> Ordering {
599         if self < other {
600             Less
601         } else if self == other {
602             Equal
603         } else {
604             Greater
605         }
606     }
607 }
608
609 #[stable(feature = "rust1", since = "1.0.0")]
610 impl<T: ?Sized> PartialOrd for *const T {
611     #[inline]
612     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
613         Some(self.cmp(other))
614     }
615
616     #[inline]
617     fn lt(&self, other: &*const T) -> bool { *self < *other }
618
619     #[inline]
620     fn le(&self, other: &*const T) -> bool { *self <= *other }
621
622     #[inline]
623     fn gt(&self, other: &*const T) -> bool { *self > *other }
624
625     #[inline]
626     fn ge(&self, other: &*const T) -> bool { *self >= *other }
627 }
628
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<T: ?Sized> Ord for *mut T {
631     #[inline]
632     fn cmp(&self, other: &*mut T) -> Ordering {
633         if self < other {
634             Less
635         } else if self == other {
636             Equal
637         } else {
638             Greater
639         }
640     }
641 }
642
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl<T: ?Sized> PartialOrd for *mut T {
645     #[inline]
646     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
647         Some(self.cmp(other))
648     }
649
650     #[inline]
651     fn lt(&self, other: &*mut T) -> bool { *self < *other }
652
653     #[inline]
654     fn le(&self, other: &*mut T) -> bool { *self <= *other }
655
656     #[inline]
657     fn gt(&self, other: &*mut T) -> bool { *self > *other }
658
659     #[inline]
660     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
661 }
662
663 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
664 /// of this wrapper owns the referent. This in turn implies that the
665 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
666 /// `*mut T` (which conveys no particular ownership semantics).  It
667 /// also implies that the referent of the pointer should not be
668 /// modified without a unique path to the `Unique` reference. Useful
669 /// for building abstractions like `Vec<T>` or `Box<T>`, which
670 /// internally use raw pointers to manage the memory that they own.
671 #[allow(missing_debug_implementations)]
672 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
673            issue = "27730")]
674 pub struct Unique<T: ?Sized> {
675     pointer: NonZero<*const T>,
676     // NOTE: this marker has no consequences for variance, but is necessary
677     // for dropck to understand that we logically own a `T`.
678     //
679     // For details, see:
680     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
681     _marker: PhantomData<T>,
682 }
683
684 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
685 /// reference is unaliased. Note that this aliasing invariant is
686 /// unenforced by the type system; the abstraction using the
687 /// `Unique` must enforce it.
688 #[unstable(feature = "unique", issue = "27730")]
689 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
690
691 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
692 /// reference is unaliased. Note that this aliasing invariant is
693 /// unenforced by the type system; the abstraction using the
694 /// `Unique` must enforce it.
695 #[unstable(feature = "unique", issue = "27730")]
696 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
697
698 #[unstable(feature = "unique", issue = "27730")]
699 impl<T: ?Sized> Unique<T> {
700     /// Creates a new `Unique`.
701     ///
702     /// # Safety
703     ///
704     /// `ptr` must be non-null.
705     pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
706         Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
707     }
708
709     /// Dereferences the content.
710     pub unsafe fn get(&self) -> &T {
711         &**self.pointer
712     }
713
714     /// Mutably dereferences the content.
715     pub unsafe fn get_mut(&mut self) -> &mut T {
716         &mut ***self
717     }
718 }
719
720 #[unstable(feature = "unique", issue = "27730")]
721 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
722
723 #[unstable(feature = "unique", issue= "27730")]
724 impl<T:?Sized> Deref for Unique<T> {
725     type Target = *mut T;
726
727     #[inline]
728     fn deref(&self) -> &*mut T {
729         unsafe { mem::transmute(&*self.pointer) }
730     }
731 }
732
733 #[stable(feature = "rust1", since = "1.0.0")]
734 impl<T> fmt::Pointer for Unique<T> {
735     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
736         fmt::Pointer::fmt(&*self.pointer, f)
737     }
738 }
739
740 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
741 /// of this wrapper has shared ownership of the referent. Useful for
742 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
743 /// use raw pointers to manage the memory that they own.
744 #[allow(missing_debug_implementations)]
745 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
746            issue = "27730")]
747 pub struct Shared<T: ?Sized> {
748     pointer: NonZero<*const T>,
749     // NOTE: this marker has no consequences for variance, but is necessary
750     // for dropck to understand that we logically own a `T`.
751     //
752     // For details, see:
753     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
754     _marker: PhantomData<T>,
755 }
756
757 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
758 // NB: This impl is unnecessary, but should provide better error messages.
759 #[unstable(feature = "shared", issue = "27730")]
760 impl<T: ?Sized> !Send for Shared<T> { }
761
762 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
763 // NB: This impl is unnecessary, but should provide better error messages.
764 #[unstable(feature = "shared", issue = "27730")]
765 impl<T: ?Sized> !Sync for Shared<T> { }
766
767 #[unstable(feature = "shared", issue = "27730")]
768 impl<T: ?Sized> Shared<T> {
769     /// Creates a new `Shared`.
770     ///
771     /// # Safety
772     ///
773     /// `ptr` must be non-null.
774     pub unsafe fn new(ptr: *mut T) -> Self {
775         Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
776     }
777 }
778
779 #[unstable(feature = "shared", issue = "27730")]
780 impl<T: ?Sized> Clone for Shared<T> {
781     fn clone(&self) -> Self {
782         *self
783     }
784 }
785
786 #[unstable(feature = "shared", issue = "27730")]
787 impl<T: ?Sized> Copy for Shared<T> { }
788
789 #[unstable(feature = "shared", issue = "27730")]
790 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
791
792 #[unstable(feature = "shared", issue = "27730")]
793 impl<T: ?Sized> Deref for Shared<T> {
794     type Target = *mut T;
795
796     #[inline]
797     fn deref(&self) -> &*mut T {
798         unsafe { mem::transmute(&*self.pointer) }
799     }
800 }
801
802 #[unstable(feature = "shared", issue = "27730")]
803 impl<T> fmt::Pointer for Shared<T> {
804     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
805         fmt::Pointer::fmt(&*self.pointer, f)
806     }
807 }