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