]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr.rs
Minor fixups to fix tidy errors
[rust.git] / src / libcore / ptr.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory
12
13 //! Raw, unsafe pointers, `*const T`, and `*mut T`.
14 //!
15 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
16
17 #![stable(feature = "rust1", since = "1.0.0")]
18
19 use intrinsics;
20 use ops::{CoerceUnsized, Deref};
21 use fmt;
22 use hash;
23 use marker::{PhantomData, Unsize};
24 use mem;
25 use nonzero::NonZero;
26
27 use cmp::Ordering::{self, Less, Equal, Greater};
28
29 // FIXME #19649: intrinsic docs don't render, so these have no docs :(
30
31 #[stable(feature = "rust1", since = "1.0.0")]
32 pub use intrinsics::copy_nonoverlapping;
33
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use intrinsics::copy;
36
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use intrinsics::write_bytes;
39
40 #[stable(feature = "drop_in_place", since = "1.8.0")]
41 pub use intrinsics::drop_in_place;
42
43 /// Creates a null raw pointer.
44 ///
45 /// # Examples
46 ///
47 /// ```
48 /// use std::ptr;
49 ///
50 /// let p: *const i32 = ptr::null();
51 /// assert!(p.is_null());
52 /// ```
53 #[inline]
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub const fn null<T>() -> *const T { 0 as *const T }
56
57 /// Creates a null mutable raw pointer.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use std::ptr;
63 ///
64 /// let p: *mut i32 = ptr::null_mut();
65 /// assert!(p.is_null());
66 /// ```
67 #[inline]
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
70
71 /// Swaps the values at two mutable locations of the same type, without
72 /// deinitializing either. They may overlap, unlike `mem::swap` which is
73 /// otherwise equivalent.
74 ///
75 /// # Safety
76 ///
77 /// This function copies the memory through the raw pointers passed to it
78 /// as arguments.
79 ///
80 /// Ensure that these pointers are valid before calling `swap`.
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 /// The pointer must be aligned; use `read_unaligned` if that is not the case.
124 ///
125 /// # Examples
126 ///
127 /// Basic usage:
128 ///
129 /// ```
130 /// let x = 12;
131 /// let y = &x as *const i32;
132 ///
133 /// unsafe {
134 ///     assert_eq!(std::ptr::read(y), 12);
135 /// }
136 /// ```
137 #[inline(always)]
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub unsafe fn read<T>(src: *const T) -> T {
140     let mut tmp: T = mem::uninitialized();
141     copy_nonoverlapping(src, &mut tmp, 1);
142     tmp
143 }
144
145 /// Reads the value from `src` without moving it. This leaves the
146 /// memory in `src` unchanged.
147 ///
148 /// Unlike `read`, the pointer may be unaligned.
149 ///
150 /// # Safety
151 ///
152 /// Beyond accepting a raw pointer, this is unsafe because it semantically
153 /// moves the value out of `src` without preventing further usage of `src`.
154 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
155 /// `src` is not used before the data is overwritten again (e.g. with `write`,
156 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
157 /// because it will attempt to drop the value previously at `*src`.
158 ///
159 /// # Examples
160 ///
161 /// Basic usage:
162 ///
163 /// ```
164 /// let x = 12;
165 /// let y = &x as *const i32;
166 ///
167 /// unsafe {
168 ///     assert_eq!(std::ptr::read_unaligned(y), 12);
169 /// }
170 /// ```
171 #[inline(always)]
172 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
173 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
174     let mut tmp: T = mem::uninitialized();
175     copy_nonoverlapping(src as *const u8,
176                         &mut tmp as *mut T as *mut u8,
177                         mem::size_of::<T>());
178     tmp
179 }
180
181 /// Overwrites a memory location with the given value without reading or
182 /// dropping the old value.
183 ///
184 /// # Safety
185 ///
186 /// This operation is marked unsafe because it accepts a raw pointer.
187 ///
188 /// It does not drop the contents of `dst`. This is safe, but it could leak
189 /// allocations or resources, so care must be taken not to overwrite an object
190 /// that should be dropped.
191 ///
192 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
193 /// location pointed to by `dst`.
194 ///
195 /// This is appropriate for initializing uninitialized memory, or overwriting
196 /// memory that has previously been `read` from.
197 ///
198 /// The pointer must be aligned; use `write_unaligned` if that is not the case.
199 ///
200 /// # Examples
201 ///
202 /// Basic usage:
203 ///
204 /// ```
205 /// let mut x = 0;
206 /// let y = &mut x as *mut i32;
207 /// let z = 12;
208 ///
209 /// unsafe {
210 ///     std::ptr::write(y, z);
211 ///     assert_eq!(std::ptr::read(y), 12);
212 /// }
213 /// ```
214 #[inline]
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub unsafe fn write<T>(dst: *mut T, src: T) {
217     intrinsics::move_val_init(&mut *dst, src)
218 }
219
220 /// Overwrites a memory location with the given value without reading or
221 /// dropping the old value.
222 ///
223 /// Unlike `write`, the pointer may be unaligned.
224 ///
225 /// # Safety
226 ///
227 /// This operation is marked unsafe because it accepts a raw pointer.
228 ///
229 /// It does not drop the contents of `dst`. This is safe, but it could leak
230 /// allocations or resources, so care must be taken not to overwrite an object
231 /// that should be dropped.
232 ///
233 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
234 /// location pointed to by `dst`.
235 ///
236 /// This is appropriate for initializing uninitialized memory, or overwriting
237 /// memory that has previously been `read` from.
238 ///
239 /// # Examples
240 ///
241 /// Basic usage:
242 ///
243 /// ```
244 /// let mut x = 0;
245 /// let y = &mut x as *mut i32;
246 /// let z = 12;
247 ///
248 /// unsafe {
249 ///     std::ptr::write_unaligned(y, z);
250 ///     assert_eq!(std::ptr::read_unaligned(y), 12);
251 /// }
252 /// ```
253 #[inline]
254 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
255 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
256     copy_nonoverlapping(&src as *const T as *const u8,
257                         dst as *mut u8,
258                         mem::size_of::<T>());
259     mem::forget(src);
260 }
261
262 /// Performs a volatile read of the value from `src` without moving it. This
263 /// leaves the memory in `src` unchanged.
264 ///
265 /// Volatile operations are intended to act on I/O memory, and are guaranteed
266 /// to not be elided or reordered by the compiler across other volatile
267 /// operations.
268 ///
269 /// # Notes
270 ///
271 /// Rust does not currently have a rigorously and formally defined memory model,
272 /// so the precise semantics of what "volatile" means here is subject to change
273 /// over time. That being said, the semantics will almost always end up pretty
274 /// similar to [C11's definition of volatile][c11].
275 ///
276 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
277 ///
278 /// # Safety
279 ///
280 /// Beyond accepting a raw pointer, this is unsafe because it semantically
281 /// moves the value out of `src` without preventing further usage of `src`.
282 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
283 /// `src` is not used before the data is overwritten again (e.g. with `write`,
284 /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
285 /// because it will attempt to drop the value previously at `*src`.
286 ///
287 /// # Examples
288 ///
289 /// Basic usage:
290 ///
291 /// ```
292 /// let x = 12;
293 /// let y = &x as *const i32;
294 ///
295 /// unsafe {
296 ///     assert_eq!(std::ptr::read_volatile(y), 12);
297 /// }
298 /// ```
299 #[inline]
300 #[stable(feature = "volatile", since = "1.9.0")]
301 pub unsafe fn read_volatile<T>(src: *const T) -> T {
302     intrinsics::volatile_load(src)
303 }
304
305 /// Performs a volatile write of a memory location with the given value without
306 /// reading or dropping the old value.
307 ///
308 /// Volatile operations are intended to act on I/O memory, and are guaranteed
309 /// to not be elided or reordered by the compiler across other volatile
310 /// operations.
311 ///
312 /// # Notes
313 ///
314 /// Rust does not currently have a rigorously and formally defined memory model,
315 /// so the precise semantics of what "volatile" means here is subject to change
316 /// over time. That being said, the semantics will almost always end up pretty
317 /// similar to [C11's definition of volatile][c11].
318 ///
319 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
320 ///
321 /// # Safety
322 ///
323 /// This operation is marked unsafe because it accepts a raw pointer.
324 ///
325 /// It does not drop the contents of `dst`. This is safe, but it could leak
326 /// allocations or resources, so care must be taken not to overwrite an object
327 /// that should be dropped.
328 ///
329 /// This is appropriate for initializing uninitialized memory, or overwriting
330 /// memory that has previously been `read` from.
331 ///
332 /// # Examples
333 ///
334 /// Basic usage:
335 ///
336 /// ```
337 /// let mut x = 0;
338 /// let y = &mut x as *mut i32;
339 /// let z = 12;
340 ///
341 /// unsafe {
342 ///     std::ptr::write_volatile(y, z);
343 ///     assert_eq!(std::ptr::read_volatile(y), 12);
344 /// }
345 /// ```
346 #[inline]
347 #[stable(feature = "volatile", since = "1.9.0")]
348 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
349     intrinsics::volatile_store(dst, src);
350 }
351
352 #[lang = "const_ptr"]
353 impl<T: ?Sized> *const T {
354     /// Returns true if the pointer is null.
355     ///
356     /// # Examples
357     ///
358     /// Basic usage:
359     ///
360     /// ```
361     /// let s: &str = "Follow the rabbit";
362     /// let ptr: *const u8 = s.as_ptr();
363     /// assert!(!ptr.is_null());
364     /// ```
365     #[stable(feature = "rust1", since = "1.0.0")]
366     #[inline]
367     pub fn is_null(self) -> bool where T: Sized {
368         self == null()
369     }
370
371     /// Returns `None` if the pointer is null, or else returns a reference to
372     /// the value wrapped in `Some`.
373     ///
374     /// # Safety
375     ///
376     /// While this method and its mutable counterpart are useful for
377     /// null-safety, it is important to note that this is still an unsafe
378     /// operation because the returned value could be pointing to invalid
379     /// memory.
380     ///
381     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
382     /// not necessarily reflect the actual lifetime of the data.
383     ///
384     /// # Examples
385     ///
386     /// Basic usage:
387     ///
388     /// ```ignore
389     /// let val: *const u8 = &10u8 as *const u8;
390     ///
391     /// unsafe {
392     ///     if let Some(val_back) = val.as_ref() {
393     ///         println!("We got back the value: {}!", val_back);
394     ///     }
395     /// }
396     /// ```
397     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
398     #[inline]
399     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
400         if self.is_null() {
401             None
402         } else {
403             Some(&*self)
404         }
405     }
406
407     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
408     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
409     ///
410     /// # Safety
411     ///
412     /// Both the starting and resulting pointer must be either in bounds or one
413     /// byte past the end of an allocated object. If either pointer is out of
414     /// bounds or arithmetic overflow occurs then
415     /// any further use of the returned value will result in undefined behavior.
416     ///
417     /// # Examples
418     ///
419     /// Basic usage:
420     ///
421     /// ```
422     /// let s: &str = "123";
423     /// let ptr: *const u8 = s.as_ptr();
424     ///
425     /// unsafe {
426     ///     println!("{}", *ptr.offset(1) as char);
427     ///     println!("{}", *ptr.offset(2) as char);
428     /// }
429     /// ```
430     #[stable(feature = "rust1", since = "1.0.0")]
431     #[inline]
432     pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
433         intrinsics::offset(self, count)
434     }
435
436     /// Calculates the offset from a pointer using wrapping arithmetic.
437     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
438     /// offset of `3 * sizeof::<T>()` bytes.
439     ///
440     /// # Safety
441     ///
442     /// The resulting pointer does not need to be in bounds, but it is
443     /// potentially hazardous to dereference (which requires `unsafe`).
444     ///
445     /// Always use `.offset(count)` instead when possible, because `offset`
446     /// allows the compiler to optimize better.
447     ///
448     /// # Examples
449     ///
450     /// Basic usage:
451     ///
452     /// ```
453     /// // Iterate using a raw pointer in increments of two elements
454     /// let data = [1u8, 2, 3, 4, 5];
455     /// let mut ptr: *const u8 = data.as_ptr();
456     /// let step = 2;
457     /// let end_rounded_up = ptr.wrapping_offset(6);
458     ///
459     /// // This loop prints "1, 3, 5, "
460     /// while ptr != end_rounded_up {
461     ///     unsafe {
462     ///         print!("{}, ", *ptr);
463     ///     }
464     ///     ptr = ptr.wrapping_offset(step);
465     /// }
466     /// ```
467     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
468     #[inline]
469     pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
470         unsafe {
471             intrinsics::arith_offset(self, count)
472         }
473     }
474 }
475
476 #[lang = "mut_ptr"]
477 impl<T: ?Sized> *mut T {
478     /// Returns true if the pointer is null.
479     ///
480     /// # Examples
481     ///
482     /// Basic usage:
483     ///
484     /// ```
485     /// let mut s = [1, 2, 3];
486     /// let ptr: *mut u32 = s.as_mut_ptr();
487     /// assert!(!ptr.is_null());
488     /// ```
489     #[stable(feature = "rust1", since = "1.0.0")]
490     #[inline]
491     pub fn is_null(self) -> bool where T: Sized {
492         self == null_mut()
493     }
494
495     /// Returns `None` if the pointer is null, or else returns a reference to
496     /// the value wrapped in `Some`.
497     ///
498     /// # Safety
499     ///
500     /// While this method and its mutable counterpart are useful for
501     /// null-safety, it is important to note that this is still an unsafe
502     /// operation because the returned value could be pointing to invalid
503     /// memory.
504     ///
505     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
506     /// not necessarily reflect the actual lifetime of the data.
507     ///
508     /// # Examples
509     ///
510     /// Basic usage:
511     ///
512     /// ```ignore
513     /// let val: *mut u8 = &mut 10u8 as *mut u8;
514     ///
515     /// unsafe {
516     ///     if let Some(val_back) = val.as_ref() {
517     ///         println!("We got back the value: {}!", val_back);
518     ///     }
519     /// }
520     /// ```
521     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
522     #[inline]
523     pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
524         if self.is_null() {
525             None
526         } else {
527             Some(&*self)
528         }
529     }
530
531     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
532     /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
533     ///
534     /// # Safety
535     ///
536     /// The offset must be in-bounds of the object, or one-byte-past-the-end.
537     /// Otherwise `offset` invokes Undefined Behavior, regardless of whether
538     /// the pointer is used.
539     ///
540     /// # Examples
541     ///
542     /// Basic usage:
543     ///
544     /// ```
545     /// let mut s = [1, 2, 3];
546     /// let ptr: *mut u32 = s.as_mut_ptr();
547     ///
548     /// unsafe {
549     ///     println!("{}", *ptr.offset(1));
550     ///     println!("{}", *ptr.offset(2));
551     /// }
552     /// ```
553     #[stable(feature = "rust1", since = "1.0.0")]
554     #[inline]
555     pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
556         intrinsics::offset(self, count) as *mut T
557     }
558
559     /// Calculates the offset from a pointer using wrapping arithmetic.
560     /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
561     /// offset of `3 * sizeof::<T>()` bytes.
562     ///
563     /// # Safety
564     ///
565     /// The resulting pointer does not need to be in bounds, but it is
566     /// potentially hazardous to dereference (which requires `unsafe`).
567     ///
568     /// Always use `.offset(count)` instead when possible, because `offset`
569     /// allows the compiler to optimize better.
570     ///
571     /// # Examples
572     ///
573     /// Basic usage:
574     ///
575     /// ```
576     /// // Iterate using a raw pointer in increments of two elements
577     /// let mut data = [1u8, 2, 3, 4, 5];
578     /// let mut ptr: *mut u8 = data.as_mut_ptr();
579     /// let step = 2;
580     /// let end_rounded_up = ptr.wrapping_offset(6);
581     ///
582     /// while ptr != end_rounded_up {
583     ///     unsafe {
584     ///         *ptr = 0;
585     ///     }
586     ///     ptr = ptr.wrapping_offset(step);
587     /// }
588     /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
589     /// ```
590     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
591     #[inline]
592     pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
593         unsafe {
594             intrinsics::arith_offset(self, count) as *mut T
595         }
596     }
597
598     /// Returns `None` if the pointer is null, or else returns a mutable
599     /// reference to the value wrapped in `Some`.
600     ///
601     /// # Safety
602     ///
603     /// As with `as_ref`, this is unsafe because it cannot verify the validity
604     /// of the returned pointer, nor can it ensure that the lifetime `'a`
605     /// returned is indeed a valid lifetime for the contained data.
606     ///
607     /// # Examples
608     ///
609     /// Basic usage:
610     ///
611     /// ```
612     /// let mut s = [1, 2, 3];
613     /// let ptr: *mut u32 = s.as_mut_ptr();
614     /// let first_value = unsafe { ptr.as_mut().unwrap() };
615     /// *first_value = 4;
616     /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
617     /// ```
618     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
619     #[inline]
620     pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
621         if self.is_null() {
622             None
623         } else {
624             Some(&mut *self)
625         }
626     }
627 }
628
629 // Equality for pointers
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl<T: ?Sized> PartialEq for *const T {
632     #[inline]
633     fn eq(&self, other: &*const T) -> bool { *self == *other }
634 }
635
636 #[stable(feature = "rust1", since = "1.0.0")]
637 impl<T: ?Sized> Eq for *const T {}
638
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl<T: ?Sized> PartialEq for *mut T {
641     #[inline]
642     fn eq(&self, other: &*mut T) -> bool { *self == *other }
643 }
644
645 #[stable(feature = "rust1", since = "1.0.0")]
646 impl<T: ?Sized> Eq for *mut T {}
647
648 /// Compare raw pointers for equality.
649 ///
650 /// This is the same as using the `==` operator, but less generic:
651 /// the arguments have to be `*const T` raw pointers,
652 /// not anything that implements `PartialEq`.
653 ///
654 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
655 /// by their address rather than comparing the values they point to
656 /// (which is what the `PartialEq for &T` implementation does).
657 ///
658 /// # Examples
659 ///
660 /// ```
661 /// use std::ptr;
662 ///
663 /// let five = 5;
664 /// let other_five = 5;
665 /// let five_ref = &five;
666 /// let same_five_ref = &five;
667 /// let other_five_ref = &other_five;
668 ///
669 /// assert!(five_ref == same_five_ref);
670 /// assert!(five_ref == other_five_ref);
671 ///
672 /// assert!(ptr::eq(five_ref, same_five_ref));
673 /// assert!(!ptr::eq(five_ref, other_five_ref));
674 /// ```
675 #[stable(feature = "ptr_eq", since = "1.17.0")]
676 #[inline]
677 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
678     a == b
679 }
680
681 #[stable(feature = "rust1", since = "1.0.0")]
682 impl<T: ?Sized> Clone for *const T {
683     #[inline]
684     fn clone(&self) -> *const T {
685         *self
686     }
687 }
688
689 #[stable(feature = "rust1", since = "1.0.0")]
690 impl<T: ?Sized> Clone for *mut T {
691     #[inline]
692     fn clone(&self) -> *mut T {
693         *self
694     }
695 }
696
697 // Impls for function pointers
698 macro_rules! fnptr_impls_safety_abi {
699     ($FnTy: ty, $($Arg: ident),*) => {
700         #[stable(feature = "rust1", since = "1.0.0")]
701         impl<Ret, $($Arg),*> Clone for $FnTy {
702             #[inline]
703             fn clone(&self) -> Self {
704                 *self
705             }
706         }
707
708         #[stable(feature = "fnptr_impls", since = "1.4.0")]
709         impl<Ret, $($Arg),*> PartialEq for $FnTy {
710             #[inline]
711             fn eq(&self, other: &Self) -> bool {
712                 *self as usize == *other as usize
713             }
714         }
715
716         #[stable(feature = "fnptr_impls", since = "1.4.0")]
717         impl<Ret, $($Arg),*> Eq for $FnTy {}
718
719         #[stable(feature = "fnptr_impls", since = "1.4.0")]
720         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
721             #[inline]
722             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
723                 (*self as usize).partial_cmp(&(*other as usize))
724             }
725         }
726
727         #[stable(feature = "fnptr_impls", since = "1.4.0")]
728         impl<Ret, $($Arg),*> Ord for $FnTy {
729             #[inline]
730             fn cmp(&self, other: &Self) -> Ordering {
731                 (*self as usize).cmp(&(*other as usize))
732             }
733         }
734
735         #[stable(feature = "fnptr_impls", since = "1.4.0")]
736         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
737             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
738                 state.write_usize(*self as usize)
739             }
740         }
741
742         #[stable(feature = "fnptr_impls", since = "1.4.0")]
743         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
744             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
745                 fmt::Pointer::fmt(&(*self as *const ()), f)
746             }
747         }
748
749         #[stable(feature = "fnptr_impls", since = "1.4.0")]
750         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
751             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
752                 fmt::Pointer::fmt(&(*self as *const ()), f)
753             }
754         }
755     }
756 }
757
758 macro_rules! fnptr_impls_args {
759     ($($Arg: ident),+) => {
760         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
761         fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
762         fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
763         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
764         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
765         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
766     };
767     () => {
768         // No variadic functions with 0 parameters
769         fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
770         fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
771         fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
772         fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
773     };
774 }
775
776 fnptr_impls_args! { }
777 fnptr_impls_args! { A }
778 fnptr_impls_args! { A, B }
779 fnptr_impls_args! { A, B, C }
780 fnptr_impls_args! { A, B, C, D }
781 fnptr_impls_args! { A, B, C, D, E }
782 fnptr_impls_args! { A, B, C, D, E, F }
783 fnptr_impls_args! { A, B, C, D, E, F, G }
784 fnptr_impls_args! { A, B, C, D, E, F, G, H }
785 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
786 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
787 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
788 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
789
790 // Comparison for pointers
791 #[stable(feature = "rust1", since = "1.0.0")]
792 impl<T: ?Sized> Ord for *const T {
793     #[inline]
794     fn cmp(&self, other: &*const T) -> Ordering {
795         if self < other {
796             Less
797         } else if self == other {
798             Equal
799         } else {
800             Greater
801         }
802     }
803 }
804
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl<T: ?Sized> PartialOrd for *const T {
807     #[inline]
808     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
809         Some(self.cmp(other))
810     }
811
812     #[inline]
813     fn lt(&self, other: &*const T) -> bool { *self < *other }
814
815     #[inline]
816     fn le(&self, other: &*const T) -> bool { *self <= *other }
817
818     #[inline]
819     fn gt(&self, other: &*const T) -> bool { *self > *other }
820
821     #[inline]
822     fn ge(&self, other: &*const T) -> bool { *self >= *other }
823 }
824
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<T: ?Sized> Ord for *mut T {
827     #[inline]
828     fn cmp(&self, other: &*mut T) -> Ordering {
829         if self < other {
830             Less
831         } else if self == other {
832             Equal
833         } else {
834             Greater
835         }
836     }
837 }
838
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<T: ?Sized> PartialOrd for *mut T {
841     #[inline]
842     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
843         Some(self.cmp(other))
844     }
845
846     #[inline]
847     fn lt(&self, other: &*mut T) -> bool { *self < *other }
848
849     #[inline]
850     fn le(&self, other: &*mut T) -> bool { *self <= *other }
851
852     #[inline]
853     fn gt(&self, other: &*mut T) -> bool { *self > *other }
854
855     #[inline]
856     fn ge(&self, other: &*mut T) -> bool { *self >= *other }
857 }
858
859 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
860 /// of this wrapper owns the referent. This in turn implies that the
861 /// `Unique<T>` is `Send`/`Sync` if `T` is `Send`/`Sync`, unlike a raw
862 /// `*mut T` (which conveys no particular ownership semantics).  It
863 /// also implies that the referent of the pointer should not be
864 /// modified without a unique path to the `Unique` reference. Useful
865 /// for building abstractions like `Vec<T>` or `Box<T>`, which
866 /// internally use raw pointers to manage the memory that they own.
867 #[allow(missing_debug_implementations)]
868 #[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
869            issue = "27730")]
870 pub struct Unique<T: ?Sized> {
871     pointer: NonZero<*const T>,
872     // NOTE: this marker has no consequences for variance, but is necessary
873     // for dropck to understand that we logically own a `T`.
874     //
875     // For details, see:
876     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
877     _marker: PhantomData<T>,
878 }
879
880 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
881 /// reference is unaliased. Note that this aliasing invariant is
882 /// unenforced by the type system; the abstraction using the
883 /// `Unique` must enforce it.
884 #[unstable(feature = "unique", issue = "27730")]
885 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
886
887 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
888 /// reference is unaliased. Note that this aliasing invariant is
889 /// unenforced by the type system; the abstraction using the
890 /// `Unique` must enforce it.
891 #[unstable(feature = "unique", issue = "27730")]
892 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
893
894 #[unstable(feature = "unique", issue = "27730")]
895 impl<T: ?Sized> Unique<T> {
896     /// Creates a new `Unique`.
897     ///
898     /// # Safety
899     ///
900     /// `ptr` must be non-null.
901     pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
902         Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
903     }
904
905     /// Dereferences the content.
906     pub unsafe fn get(&self) -> &T {
907         &**self.pointer
908     }
909
910     /// Mutably dereferences the content.
911     pub unsafe fn get_mut(&mut self) -> &mut T {
912         &mut ***self
913     }
914 }
915
916 #[unstable(feature = "unique", issue = "27730")]
917 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
918
919 #[unstable(feature = "unique", issue= "27730")]
920 impl<T:?Sized> Deref for Unique<T> {
921     type Target = *mut T;
922
923     #[inline]
924     fn deref(&self) -> &*mut T {
925         unsafe { mem::transmute(&*self.pointer) }
926     }
927 }
928
929 #[unstable(feature = "unique", issue = "27730")]
930 impl<T> fmt::Pointer for Unique<T> {
931     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
932         fmt::Pointer::fmt(&*self.pointer, f)
933     }
934 }
935
936 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
937 /// of this wrapper has shared ownership of the referent. Useful for
938 /// building abstractions like `Rc<T>` or `Arc<T>`, which internally
939 /// use raw pointers to manage the memory that they own.
940 #[allow(missing_debug_implementations)]
941 #[unstable(feature = "shared", reason = "needs an RFC to flesh out design",
942            issue = "27730")]
943 pub struct Shared<T: ?Sized> {
944     pointer: NonZero<*const T>,
945     // NOTE: this marker has no consequences for variance, but is necessary
946     // for dropck to understand that we logically own a `T`.
947     //
948     // For details, see:
949     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
950     _marker: PhantomData<T>,
951 }
952
953 /// `Shared` pointers are not `Send` because the data they reference may be aliased.
954 // NB: This impl is unnecessary, but should provide better error messages.
955 #[unstable(feature = "shared", issue = "27730")]
956 impl<T: ?Sized> !Send for Shared<T> { }
957
958 /// `Shared` pointers are not `Sync` because the data they reference may be aliased.
959 // NB: This impl is unnecessary, but should provide better error messages.
960 #[unstable(feature = "shared", issue = "27730")]
961 impl<T: ?Sized> !Sync for Shared<T> { }
962
963 #[unstable(feature = "shared", issue = "27730")]
964 impl<T: ?Sized> Shared<T> {
965     /// Creates a new `Shared`.
966     ///
967     /// # Safety
968     ///
969     /// `ptr` must be non-null.
970     pub unsafe fn new(ptr: *const T) -> Self {
971         Shared { pointer: NonZero::new(ptr), _marker: PhantomData }
972     }
973 }
974
975 #[unstable(feature = "shared", issue = "27730")]
976 impl<T: ?Sized> Shared<T> {
977     /// Acquires the underlying pointer as a `*mut` pointer.
978     pub unsafe fn as_mut_ptr(&self) -> *mut T {
979         **self as _
980     }
981 }
982
983 #[unstable(feature = "shared", issue = "27730")]
984 impl<T: ?Sized> Clone for Shared<T> {
985     fn clone(&self) -> Self {
986         *self
987     }
988 }
989
990 #[unstable(feature = "shared", issue = "27730")]
991 impl<T: ?Sized> Copy for Shared<T> { }
992
993 #[unstable(feature = "shared", issue = "27730")]
994 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Shared<U>> for Shared<T> where T: Unsize<U> { }
995
996 #[unstable(feature = "shared", issue = "27730")]
997 impl<T: ?Sized> Deref for Shared<T> {
998     type Target = *const T;
999
1000     #[inline]
1001     fn deref(&self) -> &*const T {
1002         unsafe { mem::transmute(&*self.pointer) }
1003     }
1004 }
1005
1006 #[unstable(feature = "shared", issue = "27730")]
1007 impl<T> fmt::Pointer for Shared<T> {
1008     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1009         fmt::Pointer::fmt(&*self.pointer, f)
1010     }
1011 }