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