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