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