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