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