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