]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
rustdoc: pretty-print Unevaluated expressions in types.
[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 convert::From;
20 use intrinsics;
21 use ops::CoerceUnsized;
22 use fmt;
23 use hash;
24 use marker::{PhantomData, Unsize};
25 use mem;
26 use nonzero::NonZero;
27
28 use cmp::Ordering::{self, Less, Equal, Greater};
29
30 // FIXME #19649: intrinsic docs don't render, so these have no docs :(
31
32 #[stable(feature = "rust1", since = "1.0.0")]
33 pub use intrinsics::copy_nonoverlapping;
34
35 #[stable(feature = "rust1", since = "1.0.0")]
36 pub use intrinsics::copy;
37
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub use intrinsics::write_bytes;
40
41 /// Executes the destructor (if any) of the pointed-to value.
42 ///
43 /// This has two use cases:
44 ///
45 /// * It is *required* to use `drop_in_place` to drop unsized types like
46 ///   trait objects, because they can't be read out onto the stack and
47 ///   dropped normally.
48 ///
49 /// * It is friendlier to the optimizer to do this over `ptr::read` when
50 ///   dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
51 ///   as the compiler doesn't need to prove that it's sound to elide the
52 ///   copy.
53 ///
54 /// # Undefined Behavior
55 ///
56 /// This has all the same safety problems as `ptr::read` with respect to
57 /// invalid pointers, types, and double drops.
58 #[stable(feature = "drop_in_place", since = "1.8.0")]
59 #[lang="drop_in_place"]
60 #[allow(unconditional_recursion)]
61 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
62     // Code here does not matter - this is replaced by the
63     // real drop glue by the compiler.
64     drop_in_place(to_drop);
65 }
66
67 /// Creates a null raw pointer.
68 ///
69 /// # Examples
70 ///
71 /// ```
72 /// use std::ptr;
73 ///
74 /// let p: *const i32 = ptr::null();
75 /// assert!(p.is_null());
76 /// ```
77 #[inline]
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub const fn null<T>() -> *const T { 0 as *const T }
80
81 /// Creates a null mutable raw pointer.
82 ///
83 /// # Examples
84 ///
85 /// ```
86 /// use std::ptr;
87 ///
88 /// let p: *mut i32 = ptr::null_mut();
89 /// assert!(p.is_null());
90 /// ```
91 #[inline]
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
94
95 /// Swaps the values at two mutable locations of the same type, without
96 /// deinitializing either. They may overlap, unlike `mem::swap` which is
97 /// otherwise equivalent.
98 ///
99 /// # Safety
100 ///
101 /// This function copies the memory through the raw pointers passed to it
102 /// as arguments.
103 ///
104 /// Ensure that these pointers are valid before calling `swap`.
105 #[inline]
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
108     // Give ourselves some scratch space to work with
109     let mut tmp: T = mem::uninitialized();
110
111     // Perform the swap
112     copy_nonoverlapping(x, &mut tmp, 1);
113     copy(y, x, 1); // `x` and `y` may overlap
114     copy_nonoverlapping(&tmp, y, 1);
115
116     // y and t now point to the same thing, but we need to completely forget `tmp`
117     // because it's no longer relevant.
118     mem::forget(tmp);
119 }
120
121 /// Swaps a sequence of values at two mutable locations of the same type.
122 ///
123 /// # Safety
124 ///
125 /// The two arguments must each point to the beginning of `count` locations
126 /// of valid memory, and the two memory ranges must not overlap.
127 ///
128 /// # Examples
129 ///
130 /// Basic usage:
131 ///
132 /// ```
133 /// #![feature(swap_nonoverlapping)]
134 ///
135 /// use std::ptr;
136 ///
137 /// let mut x = [1, 2, 3, 4];
138 /// let mut y = [7, 8, 9];
139 ///
140 /// unsafe {
141 ///     ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
142 /// }
143 ///
144 /// assert_eq!(x, [7, 8, 3, 4]);
145 /// assert_eq!(y, [1, 2, 9]);
146 /// ```
147 #[inline]
148 #[unstable(feature = "swap_nonoverlapping", issue = "42818")]
149 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
150     let x = x as *mut u8;
151     let y = y as *mut u8;
152     let len = mem::size_of::<T>() * count;
153     swap_nonoverlapping_bytes(x, y, len)
154 }
155
156 #[inline]
157 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
158     // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
159     // that swapping either 32 bytes or 64 bytes at a time is most efficient for intel
160     // Haswell E processors. LLVM is more able to optimize if we give a struct a
161     // #[repr(simd)], even if we don't actually use this struct directly.
162     //
163     // FIXME repr(simd) broken on emscripten and redox
164     // It's also broken on big-endian powerpc64 and s390x.  #42778
165     #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox",
166                        target_endian = "big")),
167                repr(simd))]
168     struct Block(u64, u64, u64, u64);
169     struct UnalignedBlock(u64, u64, u64, u64);
170
171     let block_size = mem::size_of::<Block>();
172
173     // Loop through x & y, copying them `Block` at a time
174     // The optimizer should unroll the loop fully for most types
175     // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
176     let mut i = 0;
177     while i + block_size <= len {
178         // Create some uninitialized memory as scratch space
179         // Declaring `t` here avoids aligning the stack when this loop is unused
180         let mut t: Block = mem::uninitialized();
181         let t = &mut t as *mut _ as *mut u8;
182         let x = x.offset(i as isize);
183         let y = y.offset(i as isize);
184
185         // Swap a block of bytes of x & y, using t as a temporary buffer
186         // This should be optimized into efficient SIMD operations where available
187         copy_nonoverlapping(x, t, block_size);
188         copy_nonoverlapping(y, x, block_size);
189         copy_nonoverlapping(t, y, block_size);
190         i += block_size;
191     }
192
193     if i < len {
194         // Swap any remaining bytes
195         let mut t: UnalignedBlock = mem::uninitialized();
196         let rem = len - i;
197
198         let t = &mut t as *mut _ as *mut u8;
199         let x = x.offset(i as isize);
200         let y = y.offset(i as isize);
201
202         copy_nonoverlapping(x, t, rem);
203         copy_nonoverlapping(y, x, rem);
204         copy_nonoverlapping(t, y, rem);
205     }
206 }
207
208 /// Replaces the value at `dest` with `src`, returning the old
209 /// value, without dropping either.
210 ///
211 /// # Safety
212 ///
213 /// This is only unsafe because it accepts a raw pointer.
214 /// Otherwise, this operation is identical to `mem::replace`.
215 #[inline]
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
218     mem::swap(&mut *dest, &mut src); // cannot overlap
219     src
220 }
221
222 /// Reads the value from `src` without moving it. This leaves the
223 /// memory in `src` unchanged.
224 ///
225 /// # Safety
226 ///
227 /// Beyond accepting a raw pointer, this is unsafe because it semantically
228 /// moves the value out of `src` without preventing further usage of `src`.
229 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
230 /// `src` is not used before the data is overwritten again (e.g. with `write`,
231 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
232 /// because it will attempt to drop the value previously at `*src`.
233 ///
234 /// The pointer must be aligned; use `read_unaligned` if that is not the case.
235 ///
236 /// # Examples
237 ///
238 /// Basic usage:
239 ///
240 /// ```
241 /// let x = 12;
242 /// let y = &x as *const i32;
243 ///
244 /// unsafe {
245 ///     assert_eq!(std::ptr::read(y), 12);
246 /// }
247 /// ```
248 #[inline]
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub unsafe fn read<T>(src: *const T) -> T {
251     let mut tmp: T = mem::uninitialized();
252     copy_nonoverlapping(src, &mut tmp, 1);
253     tmp
254 }
255
256 /// Reads the value from `src` without moving it. This leaves the
257 /// memory in `src` unchanged.
258 ///
259 /// Unlike `read`, the pointer may be unaligned.
260 ///
261 /// # Safety
262 ///
263 /// Beyond accepting a raw pointer, this is unsafe because it semantically
264 /// moves the value out of `src` without preventing further usage of `src`.
265 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
266 /// `src` is not used before the data is overwritten again (e.g. with `write`,
267 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
268 /// because it will attempt to drop the value previously at `*src`.
269 ///
270 /// # Examples
271 ///
272 /// Basic usage:
273 ///
274 /// ```
275 /// let x = 12;
276 /// let y = &x as *const i32;
277 ///
278 /// unsafe {
279 ///     assert_eq!(std::ptr::read_unaligned(y), 12);
280 /// }
281 /// ```
282 #[inline]
283 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
284 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
285     let mut tmp: T = mem::uninitialized();
286     copy_nonoverlapping(src as *const u8,
287                         &mut tmp as *mut T as *mut u8,
288                         mem::size_of::<T>());
289     tmp
290 }
291
292 /// Overwrites a memory location with the given value without reading or
293 /// dropping the old value.
294 ///
295 /// # Safety
296 ///
297 /// This operation is marked unsafe because it accepts a raw pointer.
298 ///
299 /// It does not drop the contents of `dst`. This is safe, but it could leak
300 /// allocations or resources, so care must be taken not to overwrite an object
301 /// that should be dropped.
302 ///
303 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
304 /// location pointed to by `dst`.
305 ///
306 /// This is appropriate for initializing uninitialized memory, or overwriting
307 /// memory that has previously been `read` from.
308 ///
309 /// The pointer must be aligned; use `write_unaligned` if that is not the case.
310 ///
311 /// # Examples
312 ///
313 /// Basic usage:
314 ///
315 /// ```
316 /// let mut x = 0;
317 /// let y = &mut x as *mut i32;
318 /// let z = 12;
319 ///
320 /// unsafe {
321 ///     std::ptr::write(y, z);
322 ///     assert_eq!(std::ptr::read(y), 12);
323 /// }
324 /// ```
325 #[inline]
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub unsafe fn write<T>(dst: *mut T, src: T) {
328     intrinsics::move_val_init(&mut *dst, src)
329 }
330
331 /// Overwrites a memory location with the given value without reading or
332 /// dropping the old value.
333 ///
334 /// Unlike `write`, the pointer may be unaligned.
335 ///
336 /// # Safety
337 ///
338 /// This operation is marked unsafe because it accepts a raw pointer.
339 ///
340 /// It does not drop the contents of `dst`. This is safe, but it could leak
341 /// allocations or resources, so care must be taken not to overwrite an object
342 /// that should be dropped.
343 ///
344 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
345 /// location pointed to by `dst`.
346 ///
347 /// This is appropriate for initializing uninitialized memory, or overwriting
348 /// memory that has previously been `read` from.
349 ///
350 /// # Examples
351 ///
352 /// Basic usage:
353 ///
354 /// ```
355 /// let mut x = 0;
356 /// let y = &mut x as *mut i32;
357 /// let z = 12;
358 ///
359 /// unsafe {
360 ///     std::ptr::write_unaligned(y, z);
361 ///     assert_eq!(std::ptr::read_unaligned(y), 12);
362 /// }
363 /// ```
364 #[inline]
365 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
366 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
367     copy_nonoverlapping(&src as *const T as *const u8,
368                         dst as *mut u8,
369                         mem::size_of::<T>());
370     mem::forget(src);
371 }
372
373 /// Performs a volatile read of the value from `src` without moving it. This
374 /// leaves the memory in `src` unchanged.
375 ///
376 /// Volatile operations are intended to act on I/O memory, and are guaranteed
377 /// to not be elided or reordered by the compiler across other volatile
378 /// operations.
379 ///
380 /// # Notes
381 ///
382 /// Rust does not currently have a rigorously and formally defined memory model,
383 /// so the precise semantics of what "volatile" means here is subject to change
384 /// over time. That being said, the semantics will almost always end up pretty
385 /// similar to [C11's definition of volatile][c11].
386 ///
387 /// The compiler shouldn't change the relative order or number of volatile
388 /// memory operations. However, volatile memory operations on zero-sized types
389 /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
390 /// and may be ignored.
391 ///
392 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
393 ///
394 /// # Safety
395 ///
396 /// Beyond accepting a raw pointer, this is unsafe because it semantically
397 /// moves the value out of `src` without preventing further usage of `src`.
398 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
399 /// `src` is not used before the data is overwritten again (e.g. with `write`,
400 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
401 /// because it will attempt to drop the value previously at `*src`.
402 ///
403 /// # Examples
404 ///
405 /// Basic usage:
406 ///
407 /// ```
408 /// let x = 12;
409 /// let y = &x as *const i32;
410 ///
411 /// unsafe {
412 ///     assert_eq!(std::ptr::read_volatile(y), 12);
413 /// }
414 /// ```
415 #[inline]
416 #[stable(feature = "volatile", since = "1.9.0")]
417 pub unsafe fn read_volatile<T>(src: *const T) -> T {
418     intrinsics::volatile_load(src)
419 }
420
421 /// Performs a volatile write of a memory location with the given value without
422 /// reading or dropping the old value.
423 ///
424 /// Volatile operations are intended to act on I/O memory, and are guaranteed
425 /// to not be elided or reordered by the compiler across other volatile
426 /// operations.
427 ///
428 /// # Notes
429 ///
430 /// Rust does not currently have a rigorously and formally defined memory model,
431 /// so the precise semantics of what "volatile" means here is subject to change
432 /// over time. That being said, the semantics will almost always end up pretty
433 /// similar to [C11's definition of volatile][c11].
434 ///
435 /// The compiler shouldn't change the relative order or number of volatile
436 /// memory operations. However, volatile memory operations on zero-sized types
437 /// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops
438 /// and may be ignored.
439 ///
440 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
441 ///
442 /// # Safety
443 ///
444 /// This operation is marked unsafe because it accepts a raw pointer.
445 ///
446 /// It does not drop the contents of `dst`. This is safe, but it could leak
447 /// allocations or resources, so care must be taken not to overwrite an object
448 /// that should be dropped.
449 ///
450 /// This is appropriate for initializing uninitialized memory, or overwriting
451 /// memory that has previously been `read` from.
452 ///
453 /// # Examples
454 ///
455 /// Basic usage:
456 ///
457 /// ```
458 /// let mut x = 0;
459 /// let y = &mut x as *mut i32;
460 /// let z = 12;
461 ///
462 /// unsafe {
463 ///     std::ptr::write_volatile(y, z);
464 ///     assert_eq!(std::ptr::read_volatile(y), 12);
465 /// }
466 /// ```
467 #[inline]
468 #[stable(feature = "volatile", since = "1.9.0")]
469 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
470     intrinsics::volatile_store(dst, src);
471 }
472
473 #[lang = "const_ptr"]
474 impl<T: ?Sized> *const T {
475     /// Returns `true` if the pointer is null.
476     ///
477     /// # Examples
478     ///
479     /// Basic usage:
480     ///
481     /// ```
482     /// let s: &str = "Follow the rabbit";
483     /// let ptr: *const u8 = s.as_ptr();
484     /// assert!(!ptr.is_null());
485     /// ```
486     #[stable(feature = "rust1", since = "1.0.0")]
487     #[inline]
488     pub fn is_null(self) -> bool where T: Sized {
489         self == null()
490     }
491
492     /// Returns `None` if the pointer is null, or else returns a reference to
493     /// the value wrapped in `Some`.
494     ///
495     /// # Safety
496     ///
497     /// While this method and its mutable counterpart are useful for
498     /// null-safety, it is important to note that this is still an unsafe
499     /// operation because the returned value could be pointing to invalid
500     /// memory.
501     ///
502     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
503     /// not necessarily reflect the actual lifetime of the data.
504     ///
505     /// # Examples
506     ///
507     /// Basic usage:
508     ///
509     /// ```
510     /// let ptr: *const u8 = &10u8 as *const u8;
511     ///
512     /// unsafe {
513     ///     if let Some(val_back) = ptr.as_ref() {
514     ///         println!("We got back the value: {}!", val_back);
515     ///     }
516     /// }
517     /// ```
518     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
519     #[inline]
520     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
521         if self.is_null() {
522             None
523         } else {
524             Some(&*self)
525         }
526     }
527
528     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
529     /// `count` of 3 represents a pointer offset of `3 * size_of::<T>()` bytes.
530     ///
531     /// # Safety
532     ///
533     /// Both the starting and resulting pointer must be either in bounds or one
534     /// byte past the end of an allocated object. If either pointer is out of
535     /// bounds or arithmetic overflow occurs then
536     /// any further use of the returned value will result in undefined behavior.
537     ///
538     /// # Examples
539     ///
540     /// Basic usage:
541     ///
542     /// ```
543     /// let s: &str = "123";
544     /// let ptr: *const u8 = s.as_ptr();
545     ///
546     /// unsafe {
547     ///     println!("{}", *ptr.offset(1) as char);
548     ///     println!("{}", *ptr.offset(2) as char);
549     /// }
550     /// ```
551     #[stable(feature = "rust1", since = "1.0.0")]
552     #[inline]
553     pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
554         intrinsics::offset(self, count)
555     }
556
557     /// Calculates the offset from a pointer using wrapping arithmetic.
558     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
559     /// offset of `3 * size_of::<T>()` bytes.
560     ///
561     /// # Safety
562     ///
563     /// The resulting pointer does not need to be in bounds, but it is
564     /// potentially hazardous to dereference (which requires `unsafe`).
565     ///
566     /// Always use `.offset(count)` instead when possible, because `offset`
567     /// allows the compiler to optimize better.
568     ///
569     /// # Examples
570     ///
571     /// Basic usage:
572     ///
573     /// ```
574     /// // Iterate using a raw pointer in increments of two elements
575     /// let data = [1u8, 2, 3, 4, 5];
576     /// let mut ptr: *const u8 = data.as_ptr();
577     /// let step = 2;
578     /// let end_rounded_up = ptr.wrapping_offset(6);
579     ///
580     /// // This loop prints "1, 3, 5, "
581     /// while ptr != end_rounded_up {
582     ///     unsafe {
583     ///         print!("{}, ", *ptr);
584     ///     }
585     ///     ptr = ptr.wrapping_offset(step);
586     /// }
587     /// ```
588     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
589     #[inline]
590     pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
591         unsafe {
592             intrinsics::arith_offset(self, count)
593         }
594     }
595
596     /// Calculates the distance between two pointers. The returned value is in
597     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
598     ///
599     /// If the address different between the two pointers ia not a multiple of
600     /// `mem::size_of::<T>()` then the result of the division is rounded towards
601     /// zero.
602     ///
603     /// This function returns `None` if `T` is a zero-sized typed.
604     ///
605     /// # Examples
606     ///
607     /// Basic usage:
608     ///
609     /// ```
610     /// #![feature(offset_to)]
611     ///
612     /// fn main() {
613     ///     let a = [0; 5];
614     ///     let ptr1: *const i32 = &a[1];
615     ///     let ptr2: *const i32 = &a[3];
616     ///     assert_eq!(ptr1.offset_to(ptr2), Some(2));
617     ///     assert_eq!(ptr2.offset_to(ptr1), Some(-2));
618     ///     assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
619     ///     assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
620     /// }
621     /// ```
622     #[unstable(feature = "offset_to", issue = "41079")]
623     #[inline]
624     pub fn offset_to(self, other: *const T) -> Option<isize> where T: Sized {
625         let size = mem::size_of::<T>();
626         if size == 0 {
627             None
628         } else {
629             let diff = (other as isize).wrapping_sub(self as isize);
630             Some(diff / size as isize)
631         }
632     }
633 }
634
635 #[lang = "mut_ptr"]
636 impl<T: ?Sized> *mut T {
637     /// Returns `true` if the pointer is null.
638     ///
639     /// # Examples
640     ///
641     /// Basic usage:
642     ///
643     /// ```
644     /// let mut s = [1, 2, 3];
645     /// let ptr: *mut u32 = s.as_mut_ptr();
646     /// assert!(!ptr.is_null());
647     /// ```
648     #[stable(feature = "rust1", since = "1.0.0")]
649     #[inline]
650     pub fn is_null(self) -> bool where T: Sized {
651         self == null_mut()
652     }
653
654     /// Returns `None` if the pointer is null, or else returns a reference to
655     /// the value wrapped in `Some`.
656     ///
657     /// # Safety
658     ///
659     /// While this method and its mutable counterpart are useful for
660     /// null-safety, it is important to note that this is still an unsafe
661     /// operation because the returned value could be pointing to invalid
662     /// memory.
663     ///
664     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
665     /// not necessarily reflect the actual lifetime of the data.
666     ///
667     /// # Examples
668     ///
669     /// Basic usage:
670     ///
671     /// ```
672     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
673     ///
674     /// unsafe {
675     ///     if let Some(val_back) = ptr.as_ref() {
676     ///         println!("We got back the value: {}!", val_back);
677     ///     }
678     /// }
679     /// ```
680     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
681     #[inline]
682     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
683         if self.is_null() {
684             None
685         } else {
686             Some(&*self)
687         }
688     }
689
690     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
691     /// `count` of 3 represents a pointer offset of `3 * size_of::<T>()` bytes.
692     ///
693     /// # Safety
694     ///
695     /// The offset must be in-bounds of the object, or one-byte-past-the-end.
696     /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
697     /// the pointer is used.
698     ///
699     /// # Examples
700     ///
701     /// Basic usage:
702     ///
703     /// ```
704     /// let mut s = [1, 2, 3];
705     /// let ptr: *mut u32 = s.as_mut_ptr();
706     ///
707     /// unsafe {
708     ///     println!("{}", *ptr.offset(1));
709     ///     println!("{}", *ptr.offset(2));
710     /// }
711     /// ```
712     #[stable(feature = "rust1", since = "1.0.0")]
713     #[inline]
714     pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
715         intrinsics::offset(self, count) as *mut T
716     }
717
718     /// Calculates the offset from a pointer using wrapping arithmetic.
719     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
720     /// offset of `3 * size_of::<T>()` bytes.
721     ///
722     /// # Safety
723     ///
724     /// The resulting pointer does not need to be in bounds, but it is
725     /// potentially hazardous to dereference (which requires `unsafe`).
726     ///
727     /// Always use `.offset(count)` instead when possible, because `offset`
728     /// allows the compiler to optimize better.
729     ///
730     /// # Examples
731     ///
732     /// Basic usage:
733     ///
734     /// ```
735     /// // Iterate using a raw pointer in increments of two elements
736     /// let mut data = [1u8, 2, 3, 4, 5];
737     /// let mut ptr: *mut u8 = data.as_mut_ptr();
738     /// let step = 2;
739     /// let end_rounded_up = ptr.wrapping_offset(6);
740     ///
741     /// while ptr != end_rounded_up {
742     ///     unsafe {
743     ///         *ptr = 0;
744     ///     }
745     ///     ptr = ptr.wrapping_offset(step);
746     /// }
747     /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
748     /// ```
749     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
750     #[inline]
751     pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
752         unsafe {
753             intrinsics::arith_offset(self, count) as *mut T
754         }
755     }
756
757     /// Returns `None` if the pointer is null, or else returns a mutable
758     /// reference to the value wrapped in `Some`.
759     ///
760     /// # Safety
761     ///
762     /// As with `as_ref`, this is unsafe because it cannot verify the validity
763     /// of the returned pointer, nor can it ensure that the lifetime `'a`
764     /// returned is indeed a valid lifetime for the contained data.
765     ///
766     /// # Examples
767     ///
768     /// Basic usage:
769     ///
770     /// ```
771     /// let mut s = [1, 2, 3];
772     /// let ptr: *mut u32 = s.as_mut_ptr();
773     /// let first_value = unsafe { ptr.as_mut().unwrap() };
774     /// *first_value = 4;
775     /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
776     /// ```
777     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
778     #[inline]
779     pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
780         if self.is_null() {
781             None
782         } else {
783             Some(&mut *self)
784         }
785     }
786
787     /// Calculates the distance between two pointers. The returned value is in
788     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
789     ///
790     /// If the address different between the two pointers ia not a multiple of
791     /// `mem::size_of::<T>()` then the result of the division is rounded towards
792     /// zero.
793     ///
794     /// This function returns `None` if `T` is a zero-sized typed.
795     ///
796     /// # Examples
797     ///
798     /// Basic usage:
799     ///
800     /// ```
801     /// #![feature(offset_to)]
802     ///
803     /// fn main() {
804     ///     let mut a = [0; 5];
805     ///     let ptr1: *mut i32 = &mut a[1];
806     ///     let ptr2: *mut i32 = &mut a[3];
807     ///     assert_eq!(ptr1.offset_to(ptr2), Some(2));
808     ///     assert_eq!(ptr2.offset_to(ptr1), Some(-2));
809     ///     assert_eq!(unsafe { ptr1.offset(2) }, ptr2);
810     ///     assert_eq!(unsafe { ptr2.offset(-2) }, ptr1);
811     /// }
812     /// ```
813     #[unstable(feature = "offset_to", issue = "41079")]
814     #[inline]
815     pub fn offset_to(self, other: *const T) -> Option<isize> where T: Sized {
816         let size = mem::size_of::<T>();
817         if size == 0 {
818             None
819         } else {
820             let diff = (other as isize).wrapping_sub(self as isize);
821             Some(diff / size as isize)
822         }
823     }
824 }
825
826 // Equality for pointers
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl<T: ?Sized> PartialEq for *const T {
829     #[inline]
830     fn eq(&self, other: &*const T) -> bool { *self == *other }
831 }
832
833 #[stable(feature = "rust1", since = "1.0.0")]
834 impl<T: ?Sized> Eq for *const T {}
835
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<T: ?Sized> PartialEq for *mut T {
838     #[inline]
839     fn eq(&self, other: &*mut T) -> bool { *self == *other }
840 }
841
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<T: ?Sized> Eq for *mut T {}
844
845 /// Compare raw pointers for equality.
846 ///
847 /// This is the same as using the `==` operator, but less generic:
848 /// the arguments have to be `*const T` raw pointers,
849 /// not anything that implements `PartialEq`.
850 ///
851 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
852 /// by their address rather than comparing the values they point to
853 /// (which is what the `PartialEq for &T` implementation does).
854 ///
855 /// # Examples
856 ///
857 /// ```
858 /// use std::ptr;
859 ///
860 /// let five = 5;
861 /// let other_five = 5;
862 /// let five_ref = &five;
863 /// let same_five_ref = &five;
864 /// let other_five_ref = &other_five;
865 ///
866 /// assert!(five_ref == same_five_ref);
867 /// assert!(five_ref == other_five_ref);
868 ///
869 /// assert!(ptr::eq(five_ref, same_five_ref));
870 /// assert!(!ptr::eq(five_ref, other_five_ref));
871 /// ```
872 #[stable(feature = "ptr_eq", since = "1.17.0")]
873 #[inline]
874 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
875     a == b
876 }
877
878 // Impls for function pointers
879 macro_rules! fnptr_impls_safety_abi {
880     ($FnTy: ty, $($Arg: ident),*) => {
881         #[stable(feature = "fnptr_impls", since = "1.4.0")]
882         impl<Ret, $($Arg),*> PartialEq for $FnTy {
883             #[inline]
884             fn eq(&self, other: &Self) -> bool {
885                 *self as usize == *other as usize
886             }
887         }
888
889         #[stable(feature = "fnptr_impls", since = "1.4.0")]
890         impl<Ret, $($Arg),*> Eq for $FnTy {}
891
892         #[stable(feature = "fnptr_impls", since = "1.4.0")]
893         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
894             #[inline]
895             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
896                 (*self as usize).partial_cmp(&(*other as usize))
897             }
898         }
899
900         #[stable(feature = "fnptr_impls", since = "1.4.0")]
901         impl<Ret, $($Arg),*> Ord for $FnTy {
902             #[inline]
903             fn cmp(&self, other: &Self) -> Ordering {
904                 (*self as usize).cmp(&(*other as usize))
905             }
906         }
907
908         #[stable(feature = "fnptr_impls", since = "1.4.0")]
909         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
910             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
911                 state.write_usize(*self as usize)
912             }
913         }
914
915         #[stable(feature = "fnptr_impls", since = "1.4.0")]
916         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
917             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
918                 fmt::Pointer::fmt(&(*self as *const ()), f)
919             }
920         }
921
922         #[stable(feature = "fnptr_impls", since = "1.4.0")]
923         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
924             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
925                 fmt::Pointer::fmt(&(*self as *const ()), f)
926             }
927         }
928     }
929 }
930
931 macro_rules! fnptr_impls_args {
932     ($($Arg: ident),+) => {
933         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
934         fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
935         fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
936         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
937         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
938         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
939     };
940     () => {
941         // No variadic functions with 0 parameters
942         fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
943         fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
944         fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
945         fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
946     };
947 }
948
949 fnptr_impls_args! { }
950 fnptr_impls_args! { A }
951 fnptr_impls_args! { A, B }
952 fnptr_impls_args! { A, B, C }
953 fnptr_impls_args! { A, B, C, D }
954 fnptr_impls_args! { A, B, C, D, E }
955 fnptr_impls_args! { A, B, C, D, E, F }
956 fnptr_impls_args! { A, B, C, D, E, F, G }
957 fnptr_impls_args! { A, B, C, D, E, F, G, H }
958 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
959 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
960 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
961 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
962
963 // Comparison for pointers
964 #[stable(feature = "rust1", since = "1.0.0")]
965 impl<T: ?Sized> Ord for *const T {
966     #[inline]
967     fn cmp(&self, other: &*const T) -> Ordering {
968         if self < other {
969             Less
970         } else if self == other {
971             Equal
972         } else {
973             Greater
974         }
975     }
976 }
977
978 #[stable(feature = "rust1", since = "1.0.0")]
979 impl<T: ?Sized> PartialOrd for *const T {
980     #[inline]
981     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
982         Some(self.cmp(other))
983     }
984
985     #[inline]
986     fn lt(&self, other: &*const T) -> bool { *self < *other }
987
988     #[inline]
989     fn le(&self, other: &*const T) -> bool { *self <= *other }
990
991     #[inline]
992     fn gt(&self, other: &*const T) -> bool { *self > *other }
993
994     #[inline]
995     fn ge(&self, other: &*const T) -> bool { *self >= *other }
996 }
997
998 #[stable(feature = "rust1", since = "1.0.0")]
999 impl<T: ?Sized> Ord for *mut T {
1000     #[inline]
1001     fn cmp(&self, other: &*mut T) -> Ordering {
1002         if self < other {
1003             Less
1004         } else if self == other {
1005             Equal
1006         } else {
1007             Greater
1008         }
1009     }
1010 }
1011
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl<T: ?Sized> PartialOrd for *mut T {
1014     #[inline]
1015     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1016         Some(self.cmp(other))
1017     }
1018
1019     #[inline]
1020     fn lt(&self, other: &*mut T) -> bool { *self < *other }
1021
1022     #[inline]
1023     fn le(&self, other: &*mut T) -> bool { *self <= *other }
1024
1025     #[inline]
1026     fn gt(&self, other: &*mut T) -> bool { *self > *other }
1027
1028     #[inline]
1029     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
1030 }
1031
1032 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
1033 /// of this wrapper owns the referent. Useful for building abstractions like
1034 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
1035 ///
1036 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
1037 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
1038 /// the kind of strong aliasing guarantees an instance of `T` can expect:
1039 /// the referent of the pointer should not be modified without a unique path to
1040 /// its owning Unique.
1041 ///
1042 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
1043 /// consider using `Shared`, which has weaker semantics.
1044 ///
1045 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
1046 /// is never dereferenced. This is so that enums may use this forbidden value
1047 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
1048 /// However the pointer may still dangle if it isn't dereferenced.
1049 ///
1050 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
1051 /// for any type which upholds Unique's aliasing requirements.
1052 #[allow(missing_debug_implementations)]
1053 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
1054            issue = "27730")]
1055 pub struct Unique<T: ?Sized> {
1056     pointer: NonZero<*const T>,
1057     // NOTE: this marker has no consequences for variance, but is necessary
1058     // for dropck to understand that we logically own a `T`.
1059     //
1060     // For details, see:
1061     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
1062     _marker: PhantomData<T>,
1063 }
1064
1065 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
1066 /// reference is unaliased. Note that this aliasing invariant is
1067 /// unenforced by the type system; the abstraction using the
1068 /// `Unique` must enforce it.
1069 #[unstable(feature = "unique", issue = "27730")]
1070 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
1071
1072 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
1073 /// reference is unaliased. Note that this aliasing invariant is
1074 /// unenforced by the type system; the abstraction using the
1075 /// `Unique` must enforce it.
1076 #[unstable(feature = "unique", issue = "27730")]
1077 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
1078
1079 #[unstable(feature = "unique", issue = "27730")]
1080 impl<T: Sized> Unique<T> {
1081     /// Creates a new `Unique` that is dangling, but well-aligned.
1082     ///
1083     /// This is useful for initializing types which lazily allocate, like
1084     /// `Vec::new` does.
1085     pub fn empty() -> Self {
1086         unsafe {
1087             let ptr = mem::align_of::<T>() as *mut T;
1088             Unique::new_unchecked(ptr)
1089         }
1090     }
1091 }
1092
1093 #[unstable(feature = "unique", issue = "27730")]
1094 impl<T: ?Sized> Unique<T> {
1095     /// Creates a new `Unique`.
1096     ///
1097     /// # Safety
1098     ///
1099     /// `ptr` must be non-null.
1100     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
1101         Unique { pointer: NonZero::new_unchecked(ptr), _marker: PhantomData }
1102     }
1103
1104     /// Creates a new `Unique` if `ptr` is non-null.
1105     pub fn new(ptr: *mut T) -> Option<Self> {
1106         NonZero::new(ptr as *const T).map(|nz| Unique { pointer: nz, _marker: PhantomData })
1107     }
1108
1109     /// Acquires the underlying `*mut` pointer.
1110     pub fn as_ptr(self) -> *mut T {
1111         self.pointer.get() as *mut T
1112     }
1113
1114     /// Dereferences the content.
1115     ///
1116     /// The resulting lifetime is bound to self so this behaves "as if"
1117     /// it were actually an instance of T that is getting borrowed. If a longer
1118     /// (unbound) lifetime is needed, use `&*my_ptr.ptr()`.
1119     pub unsafe fn as_ref(&self) -> &T {
1120         &*self.as_ptr()
1121     }
1122
1123     /// Mutably dereferences the content.
1124     ///
1125     /// The resulting lifetime is bound to self so this behaves "as if"
1126     /// it were actually an instance of T that is getting borrowed. If a longer
1127     /// (unbound) lifetime is needed, use `&mut *my_ptr.ptr()`.
1128     pub unsafe fn as_mut(&mut self) -> &mut T {
1129         &mut *self.as_ptr()
1130     }
1131 }
1132
1133 #[unstable(feature = "unique", issue = "27730")]
1134 impl<T: ?Sized> Clone for Unique<T> {
1135     fn clone(&self) -> Self {
1136         *self
1137     }
1138 }
1139
1140 #[unstable(feature = "unique", issue = "27730")]
1141 impl<T: ?Sized> Copy for Unique<T> { }
1142
1143 #[unstable(feature = "unique", issue = "27730")]
1144 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
1145
1146 #[unstable(feature = "unique", issue = "27730")]
1147 impl<T: ?Sized> fmt::Pointer for Unique<T> {
1148     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1149         fmt::Pointer::fmt(&self.as_ptr(), f)
1150     }
1151 }
1152
1153 #[unstable(feature = "unique", issue = "27730")]
1154 impl<'a, T: ?Sized> From<&'a mut T> for Unique<T> {
1155     fn from(reference: &'a mut T) -> Self {
1156         Unique { pointer: NonZero::from(reference), _marker: PhantomData }
1157     }
1158 }
1159
1160 #[unstable(feature = "unique", issue = "27730")]
1161 impl<'a, T: ?Sized> From<&'a T> for Unique<T> {
1162     fn from(reference: &'a T) -> Self {
1163         Unique { pointer: NonZero::from(reference), _marker: PhantomData }
1164     }
1165 }
1166
1167 /// A wrapper around a raw `*mut T` that indicates that the possessor
1168 /// of this wrapper has shared ownership of the referent. Useful for
1169 /// building abstractions like `Rc<T>`, `Arc<T>`, or doubly-linked lists, which
1170 /// internally use aliased raw pointers to manage the memory that they own.
1171 ///
1172 /// This is similar to `Unique`, except that it doesn't make any aliasing
1173 /// guarantees, and doesn't derive Send and Sync. Note that unlike `&T`,
1174 /// Shared has no special mutability requirements. Shared may mutate data
1175 /// aliased by other Shared pointers. More precise rules require Rust to
1176 /// develop an actual aliasing model.
1177 ///
1178 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
1179 /// is never dereferenced. This is so that enums may use this forbidden value
1180 /// as a discriminant -- `Option<Shared<T>>` has the same size as `Shared<T>`.
1181 /// However the pointer may still dangle if it isn't dereferenced.
1182 ///
1183 /// Unlike `*mut T`, `Shared<T>` is covariant over `T`. If this is incorrect
1184 /// for your use case, you should include some PhantomData in your type to
1185 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
1186 /// Usually this won't be necessary; covariance is correct for Rc, Arc, and LinkedList
1187 /// because they provide a public API that follows the normal shared XOR mutable
1188 /// rules of Rust.
1189 #[allow(missing_debug_implementations)]
1190 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
1191            issue = "27730")]
1192 pub struct Shared<T: ?Sized> {
1193     pointer: NonZero<*const T>,
1194     // NOTE: this marker has no consequences for variance, but is necessary
1195     // for dropck to understand that we logically own a `T`.
1196     //
1197     // For details, see:
1198     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
1199     _marker: PhantomData<T>,
1200 }
1201
1202 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
1203 // NB: This impl is unnecessary, but should provide better error messages.
1204 #[unstable(feature = "shared", issue = "27730")]
1205 impl<T: ?Sized> !Send for Shared<T> { }
1206
1207 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
1208 // NB: This impl is unnecessary, but should provide better error messages.
1209 #[unstable(feature = "shared", issue = "27730")]
1210 impl<T: ?Sized> !Sync for Shared<T> { }
1211
1212 #[unstable(feature = "shared", issue = "27730")]
1213 impl<T: Sized> Shared<T> {
1214     /// Creates a new `Shared` that is dangling, but well-aligned.
1215     ///
1216     /// This is useful for initializing types which lazily allocate, like
1217     /// `Vec::new` does.
1218     pub fn empty() -> Self {
1219         unsafe {
1220             let ptr = mem::align_of::<T>() as *mut T;
1221             Shared::new_unchecked(ptr)
1222         }
1223     }
1224 }
1225
1226 #[unstable(feature = "shared", issue = "27730")]
1227 impl<T: ?Sized> Shared<T> {
1228     /// Creates a new `Shared`.
1229     ///
1230     /// # Safety
1231     ///
1232     /// `ptr` must be non-null.
1233     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
1234         Shared { pointer: NonZero::new_unchecked(ptr), _marker: PhantomData }
1235     }
1236
1237     /// Creates a new `Shared` if `ptr` is non-null.
1238     pub fn new(ptr: *mut T) -> Option<Self> {
1239         NonZero::new(ptr as *const T).map(|nz| Shared { pointer: nz, _marker: PhantomData })
1240     }
1241
1242     /// Acquires the underlying `*mut` pointer.
1243     pub fn as_ptr(self) -> *mut T {
1244         self.pointer.get() as *mut T
1245     }
1246
1247     /// Dereferences the content.
1248     ///
1249     /// The resulting lifetime is bound to self so this behaves "as if"
1250     /// it were actually an instance of T that is getting borrowed. If a longer
1251     /// (unbound) lifetime is needed, use `&*my_ptr.ptr()`.
1252     pub unsafe fn as_ref(&self) -> &T {
1253         &*self.as_ptr()
1254     }
1255
1256     /// Mutably dereferences the content.
1257     ///
1258     /// The resulting lifetime is bound to self so this behaves "as if"
1259     /// it were actually an instance of T that is getting borrowed. If a longer
1260     /// (unbound) lifetime is needed, use `&mut *my_ptr.ptr_mut()`.
1261     pub unsafe fn as_mut(&mut self) -> &mut T {
1262         &mut *self.as_ptr()
1263     }
1264
1265     /// Acquires the underlying pointer as a `*mut` pointer.
1266     #[rustc_deprecated(since = "1.19", reason = "renamed to `as_ptr` for ergonomics/consistency")]
1267     #[unstable(feature = "shared", issue = "27730")]
1268     pub unsafe fn as_mut_ptr(&self) -> *mut T {
1269         self.as_ptr()
1270     }
1271 }
1272
1273 #[unstable(feature = "shared", issue = "27730")]
1274 impl<T: ?Sized> Clone for Shared<T> {
1275     fn clone(&self) -> Self {
1276         *self
1277     }
1278 }
1279
1280 #[unstable(feature = "shared", issue = "27730")]
1281 impl<T: ?Sized> Copy for Shared<T> { }
1282
1283 #[unstable(feature = "shared", issue = "27730")]
1284 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
1285
1286 #[unstable(feature = "shared", issue = "27730")]
1287 impl<T: ?Sized> fmt::Pointer for Shared<T> {
1288     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1289         fmt::Pointer::fmt(&self.as_ptr(), f)
1290     }
1291 }
1292
1293 #[unstable(feature = "shared", issue = "27730")]
1294 impl<T: ?Sized> From<Unique<T>> for Shared<T> {
1295     fn from(unique: Unique<T>) -> Self {
1296         Shared { pointer: unique.pointer, _marker: PhantomData }
1297     }
1298 }
1299
1300 #[unstable(feature = "shared", issue = "27730")]
1301 impl<'a, T: ?Sized> From<&'a mut T> for Shared<T> {
1302     fn from(reference: &'a mut T) -> Self {
1303         Shared { pointer: NonZero::from(reference), _marker: PhantomData }
1304     }
1305 }
1306
1307 #[unstable(feature = "shared", issue = "27730")]
1308 impl<'a, T: ?Sized> From<&'a T> for Shared<T> {
1309     fn from(reference: &'a T) -> Self {
1310         Shared { pointer: NonZero::from(reference), _marker: PhantomData }
1311     }
1312 }