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