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.
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.
11 //! Manually manage memory through raw pointers.
13 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
17 //! Many functions in this module take raw pointers as arguments and read from
18 //! or write to them. For this to be safe, these pointers must be *valid*.
19 //! Whether a pointer is valid depends on the operation it is used for
20 //! (read or write), and the extent of the memory that is accessed (i.e.,
21 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
22 //! to access only a single value, in which case the documentation omits the size
23 //! and implicitly assumes it to be `size_of::<T>()` bytes.
25 //! The precise rules for validity are not determined yet. The guarantees that are
26 //! provided at this point are very minimal:
28 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
29 //! * All pointers (except for the null pointer) are valid for all operations of
31 //! * All accesses performed by functions in this module are *non-atomic* in the sense
32 //! of [atomic operations] used to synchronize between threads. This means it is
33 //! undefined behavior to perform two concurrent accesses to the same location from different
34 //! threads unless both accesses only read from memory. Notice that this explicitly
35 //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
36 //! be used for inter-thread synchronization.
37 //! * The result of casting a reference to a pointer is valid for as long as the
38 //! underlying object is live and no reference (just raw pointers) is used to
39 //! access the same memory.
41 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
42 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
43 //! will be provided eventually, as the [aliasing] rules are being determined. For more
44 //! information, see the [book] as well as the section in the reference devoted
45 //! to [undefined behavior][ub].
49 //! Valid raw pointers as defined above are not necessarily properly aligned (where
50 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
51 //! aligned to `mem::align_of::<T>()`). However, most functions require their
52 //! arguments to be properly aligned, and will explicitly state
53 //! this requirement in their documentation. Notable exceptions to this are
54 //! [`read_unaligned`] and [`write_unaligned`].
56 //! When a function requires proper alignment, it does so even if the access
57 //! has size 0, i.e., even if memory is not actually touched. Consider using
58 //! [`NonNull::dangling`] in such cases.
60 //! [aliasing]: ../../nomicon/aliasing.html
61 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
62 //! [ub]: ../../reference/behavior-considered-undefined.html
63 //! [null]: ./fn.null.html
64 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
65 //! [atomic operations]: ../../std/sync/atomic/index.html
66 //! [`copy`]: ../../std/ptr/fn.copy.html
67 //! [`offset`]: ../../std/primitive.pointer.html#method.offset
68 //! [`read_unaligned`]: ./fn.read_unaligned.html
69 //! [`write_unaligned`]: ./fn.write_unaligned.html
70 //! [`read_volatile`]: ./fn.read_volatile.html
71 //! [`write_volatile`]: ./fn.write_volatile.html
72 //! [`NonNull::dangling`]: ./struct.NonNull.html#method.dangling
74 #![stable(feature = "rust1", since = "1.0.0")]
78 use ops::{CoerceUnsized, DispatchFromDyn};
81 use marker::{PhantomData, Unsize};
82 use mem::{self, MaybeUninit};
85 use cmp::Ordering::{self, Less, Equal, Greater};
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub use intrinsics::copy_nonoverlapping;
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub use intrinsics::copy;
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub use intrinsics::write_bytes;
96 /// Executes the destructor (if any) of the pointed-to value.
98 /// This is semantically equivalent to calling [`ptr::read`] and discarding
99 /// the result, but has the following advantages:
101 /// * It is *required* to use `drop_in_place` to drop unsized types like
102 /// trait objects, because they can't be read out onto the stack and
103 /// dropped normally.
105 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
106 /// dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
107 /// as the compiler doesn't need to prove that it's sound to elide the
110 /// [`ptr::read`]: ../ptr/fn.read.html
114 /// Behavior is undefined if any of the following conditions are violated:
116 /// * `to_drop` must be [valid] for reads.
118 /// * `to_drop` must be properly aligned. See the example below for how to drop
119 /// an unaligned pointer.
121 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
122 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
123 /// foo` counts as a use because it will cause the value to be dropped
124 /// again. [`write`] can be used to overwrite data without causing it to be
127 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
129 /// [valid]: ../ptr/index.html#safety
130 /// [`Copy`]: ../marker/trait.Copy.html
131 /// [`write`]: ../ptr/fn.write.html
135 /// Manually remove the last item from a vector:
141 /// let last = Rc::new(1);
142 /// let weak = Rc::downgrade(&last);
144 /// let mut v = vec![Rc::new(0), last];
147 /// // Get a raw pointer to the last element in `v`.
148 /// let ptr = &mut v[1] as *mut _;
149 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
150 /// // to prevent issues if the `drop_in_place` below panics.
152 /// // Without a call `drop_in_place`, the last item would never be dropped,
153 /// // and the memory it manages would be leaked.
154 /// ptr::drop_in_place(ptr);
157 /// assert_eq!(v, &[0.into()]);
159 /// // Ensure that the last item was dropped.
160 /// assert!(weak.upgrade().is_none());
163 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
169 /// unsafe fn drop_after_copy<T>(to_drop: *mut T) {
170 /// let mut copy: T = mem::uninitialized();
171 /// ptr::copy(to_drop, &mut copy, 1);
175 /// #[repr(packed, C)]
178 /// unaligned: Vec<i32>,
181 /// let mut p = Packed { _padding: 0, unaligned: vec![42] };
183 /// drop_after_copy(&mut p.unaligned as *mut _);
188 /// Notice that the compiler performs this copy automatically when dropping packed structs,
189 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
191 #[stable(feature = "drop_in_place", since = "1.8.0")]
193 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
194 real_drop_in_place(&mut *to_drop)
197 // The real `drop_in_place` -- the one that gets called implicitly when variables go
198 // out of scope -- should have a safe reference and not a raw pointer as argument
199 // type. When we drop a local variable, we access it with a pointer that behaves
200 // like a safe reference; transmuting that to a raw pointer does not mean we can
201 // actually access it with raw pointers.
202 #[lang = "drop_in_place"]
203 #[allow(unconditional_recursion)]
204 unsafe fn real_drop_in_place<T: ?Sized>(to_drop: &mut T) {
205 // Code here does not matter - this is replaced by the
206 // real drop glue by the compiler.
207 real_drop_in_place(to_drop)
210 /// Creates a null raw pointer.
217 /// let p: *const i32 = ptr::null();
218 /// assert!(p.is_null());
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub const fn null<T>() -> *const T { 0 as *const T }
225 /// Creates a null mutable raw pointer.
232 /// let p: *mut i32 = ptr::null_mut();
233 /// assert!(p.is_null());
236 #[stable(feature = "rust1", since = "1.0.0")]
238 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
240 /// Swaps the values at two mutable locations of the same type, without
241 /// deinitializing either.
243 /// But for the following two exceptions, this function is semantically
244 /// equivalent to [`mem::swap`]:
246 /// * It operates on raw pointers instead of references. When references are
247 /// available, [`mem::swap`] should be preferred.
249 /// * The two pointed-to values may overlap. If the values do overlap, then the
250 /// overlapping region of memory from `x` will be used. This is demonstrated
251 /// in the second example below.
253 /// [`mem::swap`]: ../mem/fn.swap.html
257 /// Behavior is undefined if any of the following conditions are violated:
259 /// * Both `x` and `y` must be [valid] for reads and writes.
261 /// * Both `x` and `y` must be properly aligned.
263 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
265 /// [valid]: ../ptr/index.html#safety
269 /// Swapping two non-overlapping regions:
274 /// let mut array = [0, 1, 2, 3];
276 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
277 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
281 /// assert_eq!([2, 3, 0, 1], array);
285 /// Swapping two overlapping regions:
290 /// let mut array = [0, 1, 2, 3];
292 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
293 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
297 /// // The indices `1..3` of the slice overlap between `x` and `y`.
298 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
299 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
300 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
301 /// // This implementation is defined to make the latter choice.
302 /// assert_eq!([1, 0, 1, 2], array);
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
308 // Give ourselves some scratch space to work with.
309 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
310 let mut tmp = MaybeUninit::<T>::uninitialized();
313 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
314 copy(y, x, 1); // `x` and `y` may overlap
315 copy_nonoverlapping(tmp.get_ref(), y, 1);
318 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
319 /// beginning at `x` and `y`. The two regions must *not* overlap.
323 /// Behavior is undefined if any of the following conditions are violated:
325 /// * Both `x` and `y` must be [valid] for reads and writes of `count *
326 /// size_of::<T>()` bytes.
328 /// * Both `x` and `y` must be properly aligned.
330 /// * The region of memory beginning at `x` with a size of `count *
331 /// size_of::<T>()` bytes must *not* overlap with the region of memory
332 /// beginning at `y` with the same size.
334 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
335 /// the pointers must be non-NULL and properly aligned.
337 /// [valid]: ../ptr/index.html#safety
346 /// let mut x = [1, 2, 3, 4];
347 /// let mut y = [7, 8, 9];
350 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
353 /// assert_eq!(x, [7, 8, 3, 4]);
354 /// assert_eq!(y, [1, 2, 9]);
357 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
358 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
359 let x = x as *mut u8;
360 let y = y as *mut u8;
361 let len = mem::size_of::<T>() * count;
362 swap_nonoverlapping_bytes(x, y, len)
366 pub(crate) unsafe fn swap_nonoverlapping_one<T>(x: *mut T, y: *mut T) {
367 // For types smaller than the block optimization below,
368 // just swap directly to avoid pessimizing codegen.
369 if mem::size_of::<T>() < 32 {
371 copy_nonoverlapping(y, x, 1);
374 swap_nonoverlapping(x, y, 1);
379 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
380 // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
381 // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
382 // Haswell E processors. LLVM is more able to optimize if we give a struct a
383 // #[repr(simd)], even if we don't actually use this struct directly.
385 // FIXME repr(simd) broken on emscripten and redox
386 // It's also broken on big-endian powerpc64 and s390x. #42778
387 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox",
388 target_endian = "big")),
390 struct Block(u64, u64, u64, u64);
391 struct UnalignedBlock(u64, u64, u64, u64);
393 let block_size = mem::size_of::<Block>();
395 // Loop through x & y, copying them `Block` at a time
396 // The optimizer should unroll the loop fully for most types
397 // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
399 while i + block_size <= len {
400 // Create some uninitialized memory as scratch space
401 // Declaring `t` here avoids aligning the stack when this loop is unused
402 let mut t = mem::MaybeUninit::<Block>::uninitialized();
403 let t = t.as_mut_ptr() as *mut u8;
407 // Swap a block of bytes of x & y, using t as a temporary buffer
408 // This should be optimized into efficient SIMD operations where available
409 copy_nonoverlapping(x, t, block_size);
410 copy_nonoverlapping(y, x, block_size);
411 copy_nonoverlapping(t, y, block_size);
416 // Swap any remaining bytes
417 let mut t = mem::MaybeUninit::<UnalignedBlock>::uninitialized();
420 let t = t.as_mut_ptr() as *mut u8;
424 copy_nonoverlapping(x, t, rem);
425 copy_nonoverlapping(y, x, rem);
426 copy_nonoverlapping(t, y, rem);
430 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
432 /// Neither value is dropped.
434 /// This function is semantically equivalent to [`mem::replace`] except that it
435 /// operates on raw pointers instead of references. When references are
436 /// available, [`mem::replace`] should be preferred.
438 /// [`mem::replace`]: ../mem/fn.replace.html
442 /// Behavior is undefined if any of the following conditions are violated:
444 /// * `dst` must be [valid] for writes.
446 /// * `dst` must be properly aligned.
448 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
450 /// [valid]: ../ptr/index.html#safety
457 /// let mut rust = vec!['b', 'u', 's', 't'];
459 /// // `mem::replace` would have the same effect without requiring the unsafe
462 /// ptr::replace(&mut rust[0], 'r')
465 /// assert_eq!(b, 'b');
466 /// assert_eq!(rust, &['r', 'u', 's', 't']);
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
471 mem::swap(&mut *dst, &mut src); // cannot overlap
475 /// Reads the value from `src` without moving it. This leaves the
476 /// memory in `src` unchanged.
480 /// Behavior is undefined if any of the following conditions are violated:
482 /// * `src` must be [valid] for reads.
484 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
487 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
495 /// let y = &x as *const i32;
498 /// assert_eq!(std::ptr::read(y), 12);
502 /// Manually implement [`mem::swap`]:
507 /// fn swap<T>(a: &mut T, b: &mut T) {
509 /// // Create a bitwise copy of the value at `a` in `tmp`.
510 /// let tmp = ptr::read(a);
512 /// // Exiting at this point (either by explicitly returning or by
513 /// // calling a function which panics) would cause the value in `tmp` to
514 /// // be dropped while the same value is still referenced by `a`. This
515 /// // could trigger undefined behavior if `T` is not `Copy`.
517 /// // Create a bitwise copy of the value at `b` in `a`.
518 /// // This is safe because mutable references cannot alias.
519 /// ptr::copy_nonoverlapping(b, a, 1);
521 /// // As above, exiting here could trigger undefined behavior because
522 /// // the same value is referenced by `a` and `b`.
524 /// // Move `tmp` into `b`.
525 /// ptr::write(b, tmp);
527 /// // `tmp` has been moved (`write` takes ownership of its second argument),
528 /// // so nothing is dropped implicitly here.
532 /// let mut foo = "foo".to_owned();
533 /// let mut bar = "bar".to_owned();
535 /// swap(&mut foo, &mut bar);
537 /// assert_eq!(foo, "bar");
538 /// assert_eq!(bar, "foo");
541 /// ## Ownership of the Returned Value
543 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
544 /// If `T` is not [`Copy`], using both the returned value and the value at
545 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
546 /// use because it will attempt to drop the value at `*src`.
548 /// [`write`] can be used to overwrite data without causing it to be dropped.
553 /// let mut s = String::from("foo");
555 /// // `s2` now points to the same underlying memory as `s`.
556 /// let mut s2: String = ptr::read(&s);
558 /// assert_eq!(s2, "foo");
560 /// // Assigning to `s2` causes its original value to be dropped. Beyond
561 /// // this point, `s` must no longer be used, as the underlying memory has
563 /// s2 = String::default();
564 /// assert_eq!(s2, "");
566 /// // Assigning to `s` would cause the old value to be dropped again,
567 /// // resulting in undefined behavior.
568 /// // s = String::from("bar"); // ERROR
570 /// // `ptr::write` can be used to overwrite a value without dropping it.
571 /// ptr::write(&mut s, String::from("bar"));
574 /// assert_eq!(s, "bar");
577 /// [`mem::swap`]: ../mem/fn.swap.html
578 /// [valid]: ../ptr/index.html#safety
579 /// [`Copy`]: ../marker/trait.Copy.html
580 /// [`read_unaligned`]: ./fn.read_unaligned.html
581 /// [`write`]: ./fn.write.html
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub unsafe fn read<T>(src: *const T) -> T {
585 let mut tmp = MaybeUninit::<T>::uninitialized();
586 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
590 /// Reads the value from `src` without moving it. This leaves the
591 /// memory in `src` unchanged.
593 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
597 /// Behavior is undefined if any of the following conditions are violated:
599 /// * `src` must be [valid] for reads.
601 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
602 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
603 /// value and the value at `*src` can [violate memory safety][read-ownership].
605 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
607 /// [`Copy`]: ../marker/trait.Copy.html
608 /// [`read`]: ./fn.read.html
609 /// [`write_unaligned`]: ./fn.write_unaligned.html
610 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
611 /// [valid]: ../ptr/index.html#safety
615 /// Access members of a packed struct by reference:
620 /// #[repr(packed, C)]
628 /// unaligned: 0x01020304,
632 /// // Take the address of a 32-bit integer which is not aligned.
633 /// // This must be done as a raw pointer; unaligned references are invalid.
634 /// let unaligned = &x.unaligned as *const u32;
636 /// // Dereferencing normally will emit an aligned load instruction,
637 /// // causing undefined behavior.
638 /// // let v = *unaligned; // ERROR
640 /// // Instead, use `read_unaligned` to read improperly aligned values.
641 /// let v = ptr::read_unaligned(unaligned);
646 /// // Accessing unaligned values directly is safe.
647 /// assert!(x.unaligned == v);
650 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
651 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
652 let mut tmp = MaybeUninit::<T>::uninitialized();
653 copy_nonoverlapping(src as *const u8,
654 tmp.as_mut_ptr() as *mut u8,
655 mem::size_of::<T>());
659 /// Overwrites a memory location with the given value without reading or
660 /// dropping the old value.
662 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
663 /// allocations or resources, so care should be taken not to overwrite an object
664 /// that should be dropped.
666 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
667 /// location pointed to by `dst`.
669 /// This is appropriate for initializing uninitialized memory, or overwriting
670 /// memory that has previously been [`read`] from.
672 /// [`read`]: ./fn.read.html
676 /// Behavior is undefined if any of the following conditions are violated:
678 /// * `dst` must be [valid] for writes.
680 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
683 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
685 /// [valid]: ../ptr/index.html#safety
686 /// [`write_unaligned`]: ./fn.write_unaligned.html
694 /// let y = &mut x as *mut i32;
698 /// std::ptr::write(y, z);
699 /// assert_eq!(std::ptr::read(y), 12);
703 /// Manually implement [`mem::swap`]:
708 /// fn swap<T>(a: &mut T, b: &mut T) {
710 /// // Create a bitwise copy of the value at `a` in `tmp`.
711 /// let tmp = ptr::read(a);
713 /// // Exiting at this point (either by explicitly returning or by
714 /// // calling a function which panics) would cause the value in `tmp` to
715 /// // be dropped while the same value is still referenced by `a`. This
716 /// // could trigger undefined behavior if `T` is not `Copy`.
718 /// // Create a bitwise copy of the value at `b` in `a`.
719 /// // This is safe because mutable references cannot alias.
720 /// ptr::copy_nonoverlapping(b, a, 1);
722 /// // As above, exiting here could trigger undefined behavior because
723 /// // the same value is referenced by `a` and `b`.
725 /// // Move `tmp` into `b`.
726 /// ptr::write(b, tmp);
728 /// // `tmp` has been moved (`write` takes ownership of its second argument),
729 /// // so nothing is dropped implicitly here.
733 /// let mut foo = "foo".to_owned();
734 /// let mut bar = "bar".to_owned();
736 /// swap(&mut foo, &mut bar);
738 /// assert_eq!(foo, "bar");
739 /// assert_eq!(bar, "foo");
742 /// [`mem::swap`]: ../mem/fn.swap.html
744 #[stable(feature = "rust1", since = "1.0.0")]
745 pub unsafe fn write<T>(dst: *mut T, src: T) {
746 intrinsics::move_val_init(&mut *dst, src)
749 /// Overwrites a memory location with the given value without reading or
750 /// dropping the old value.
752 /// Unlike [`write`], the pointer may be unaligned.
754 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
755 /// could leak allocations or resources, so care should be taken not to overwrite
756 /// an object that should be dropped.
758 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
759 /// location pointed to by `dst`.
761 /// This is appropriate for initializing uninitialized memory, or overwriting
762 /// memory that has previously been read with [`read_unaligned`].
764 /// [`write`]: ./fn.write.html
765 /// [`read_unaligned`]: ./fn.read_unaligned.html
769 /// Behavior is undefined if any of the following conditions are violated:
771 /// * `dst` must be [valid] for writes.
773 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
775 /// [valid]: ../ptr/index.html#safety
779 /// Access fields in a packed struct:
782 /// use std::{mem, ptr};
784 /// #[repr(packed, C)]
785 /// #[derive(Default)]
791 /// let v = 0x01020304;
792 /// let mut x: Packed = unsafe { mem::zeroed() };
795 /// // Take a reference to a 32-bit integer which is not aligned.
796 /// let unaligned = &mut x.unaligned as *mut u32;
798 /// // Dereferencing normally will emit an aligned store instruction,
799 /// // causing undefined behavior because the pointer is not aligned.
800 /// // *unaligned = v; // ERROR
802 /// // Instead, use `write_unaligned` to write improperly aligned values.
803 /// ptr::write_unaligned(unaligned, v);
806 /// // Accessing unaligned values directly is safe.
807 /// assert!(x.unaligned == v);
810 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
811 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
812 copy_nonoverlapping(&src as *const T as *const u8,
814 mem::size_of::<T>());
818 /// Performs a volatile read of the value from `src` without moving it. This
819 /// leaves the memory in `src` unchanged.
821 /// Volatile operations are intended to act on I/O memory, and are guaranteed
822 /// to not be elided or reordered by the compiler across other volatile
825 /// Memory accessed with `read_volatile` or [`write_volatile`] should not be
826 /// accessed with non-volatile operations.
828 /// [`write_volatile`]: ./fn.write_volatile.html
832 /// Rust does not currently have a rigorously and formally defined memory model,
833 /// so the precise semantics of what "volatile" means here is subject to change
834 /// over time. That being said, the semantics will almost always end up pretty
835 /// similar to [C11's definition of volatile][c11].
837 /// The compiler shouldn't change the relative order or number of volatile
838 /// memory operations. However, volatile memory operations on zero-sized types
839 /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
840 /// and may be ignored.
842 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
846 /// Behavior is undefined if any of the following conditions are violated:
848 /// * `src` must be [valid] for reads.
850 /// * `src` must be properly aligned.
852 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
853 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
854 /// value and the value at `*src` can [violate memory safety][read-ownership].
855 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
858 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
860 /// [valid]: ../ptr/index.html#safety
861 /// [`Copy`]: ../marker/trait.Copy.html
862 /// [`read`]: ./fn.read.html
864 /// Just like in C, whether an operation is volatile has no bearing whatsoever
865 /// on questions involving concurrent access from multiple threads. Volatile
866 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
867 /// a race between a `read_volatile` and any write operation to the same location
868 /// is undefined behavior.
876 /// let y = &x as *const i32;
879 /// assert_eq!(std::ptr::read_volatile(y), 12);
883 #[stable(feature = "volatile", since = "1.9.0")]
884 pub unsafe fn read_volatile<T>(src: *const T) -> T {
885 intrinsics::volatile_load(src)
888 /// Performs a volatile write of a memory location with the given value without
889 /// reading or dropping the old value.
891 /// Volatile operations are intended to act on I/O memory, and are guaranteed
892 /// to not be elided or reordered by the compiler across other volatile
895 /// Memory accessed with [`read_volatile`] or `write_volatile` should not be
896 /// accessed with non-volatile operations.
898 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
899 /// could leak allocations or resources, so care should be taken not to overwrite
900 /// an object that should be dropped.
902 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
903 /// location pointed to by `dst`.
905 /// [`read_volatile`]: ./fn.read_volatile.html
909 /// Rust does not currently have a rigorously and formally defined memory model,
910 /// so the precise semantics of what "volatile" means here is subject to change
911 /// over time. That being said, the semantics will almost always end up pretty
912 /// similar to [C11's definition of volatile][c11].
914 /// The compiler shouldn't change the relative order or number of volatile
915 /// memory operations. However, volatile memory operations on zero-sized types
916 /// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops
917 /// and may be ignored.
919 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
923 /// Behavior is undefined if any of the following conditions are violated:
925 /// * `dst` must be [valid] for writes.
927 /// * `dst` must be properly aligned.
929 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
931 /// [valid]: ../ptr/index.html#safety
933 /// Just like in C, whether an operation is volatile has no bearing whatsoever
934 /// on questions involving concurrent access from multiple threads. Volatile
935 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
936 /// a race between a `write_volatile` and any other operation (reading or writing)
937 /// on the same location is undefined behavior.
945 /// let y = &mut x as *mut i32;
949 /// std::ptr::write_volatile(y, z);
950 /// assert_eq!(std::ptr::read_volatile(y), 12);
954 #[stable(feature = "volatile", since = "1.9.0")]
955 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
956 intrinsics::volatile_store(dst, src);
959 #[lang = "const_ptr"]
960 impl<T: ?Sized> *const T {
961 /// Returns `true` if the pointer is null.
963 /// Note that unsized types have many possible null pointers, as only the
964 /// raw data pointer is considered, not their length, vtable, etc.
965 /// Therefore, two pointers that are null may still not compare equal to
973 /// let s: &str = "Follow the rabbit";
974 /// let ptr: *const u8 = s.as_ptr();
975 /// assert!(!ptr.is_null());
977 #[stable(feature = "rust1", since = "1.0.0")]
979 pub fn is_null(self) -> bool {
980 // Compare via a cast to a thin pointer, so fat pointers are only
981 // considering their "data" part for null-ness.
982 (self as *const u8) == null()
985 /// Returns `None` if the pointer is null, or else returns a reference to
986 /// the value wrapped in `Some`.
990 /// While this method and its mutable counterpart are useful for
991 /// null-safety, it is important to note that this is still an unsafe
992 /// operation because the returned value could be pointing to invalid
995 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
996 /// not necessarily reflect the actual lifetime of the data.
1003 /// let ptr: *const u8 = &10u8 as *const u8;
1006 /// if let Some(val_back) = ptr.as_ref() {
1007 /// println!("We got back the value: {}!", val_back);
1012 /// # Null-unchecked version
1014 /// If you are sure the pointer can never be null and are looking for some kind of
1015 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1016 /// dereference the pointer directly.
1019 /// let ptr: *const u8 = &10u8 as *const u8;
1022 /// let val_back = &*ptr;
1023 /// println!("We got back the value: {}!", val_back);
1026 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1028 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1036 /// Calculates the offset from a pointer.
1038 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1039 /// offset of `3 * size_of::<T>()` bytes.
1043 /// If any of the following conditions are violated, the result is Undefined
1046 /// * Both the starting and resulting pointer must be either in bounds or one
1047 /// byte past the end of the same allocated object.
1049 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1051 /// * The offset being in bounds cannot rely on "wrapping around" the address
1052 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1054 /// The compiler and standard library generally tries to ensure allocations
1055 /// never reach a size where an offset is a concern. For instance, `Vec`
1056 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1057 /// `vec.as_ptr().add(vec.len())` is always safe.
1059 /// Most platforms fundamentally can't even construct such an allocation.
1060 /// For instance, no known 64-bit platform can ever serve a request
1061 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1062 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1063 /// more than `isize::MAX` bytes with things like Physical Address
1064 /// Extension. As such, memory acquired directly from allocators or memory
1065 /// mapped files *may* be too large to handle with this function.
1067 /// Consider using `wrapping_offset` instead if these constraints are
1068 /// difficult to satisfy. The only advantage of this method is that it
1069 /// enables more aggressive compiler optimizations.
1076 /// let s: &str = "123";
1077 /// let ptr: *const u8 = s.as_ptr();
1080 /// println!("{}", *ptr.offset(1) as char);
1081 /// println!("{}", *ptr.offset(2) as char);
1084 #[stable(feature = "rust1", since = "1.0.0")]
1086 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
1087 intrinsics::offset(self, count)
1090 /// Calculates the offset from a pointer using wrapping arithmetic.
1092 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1093 /// offset of `3 * size_of::<T>()` bytes.
1097 /// The resulting pointer does not need to be in bounds, but it is
1098 /// potentially hazardous to dereference (which requires `unsafe`).
1099 /// In particular, the resulting pointer may *not* be used to access a
1100 /// different allocated object than the one `self` points to. In other
1101 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1102 /// *not* the same as `y`, and dereferencing it is undefined behavior
1103 /// unless `x` and `y` point into the same allocated object.
1105 /// Always use `.offset(count)` instead when possible, because `offset`
1106 /// allows the compiler to optimize better. If you need to cross object
1107 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1114 /// // Iterate using a raw pointer in increments of two elements
1115 /// let data = [1u8, 2, 3, 4, 5];
1116 /// let mut ptr: *const u8 = data.as_ptr();
1118 /// let end_rounded_up = ptr.wrapping_offset(6);
1120 /// // This loop prints "1, 3, 5, "
1121 /// while ptr != end_rounded_up {
1123 /// print!("{}, ", *ptr);
1125 /// ptr = ptr.wrapping_offset(step);
1128 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1130 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
1132 intrinsics::arith_offset(self, count)
1136 /// Calculates the distance between two pointers. The returned value is in
1137 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1139 /// This function is the inverse of [`offset`].
1141 /// [`offset`]: #method.offset
1142 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
1146 /// If any of the following conditions are violated, the result is Undefined
1149 /// * Both the starting and other pointer must be either in bounds or one
1150 /// byte past the end of the same allocated object.
1152 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1154 /// * The distance between the pointers, in bytes, must be an exact multiple
1155 /// of the size of `T`.
1157 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1159 /// The compiler and standard library generally try to ensure allocations
1160 /// never reach a size where an offset is a concern. For instance, `Vec`
1161 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1162 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1164 /// Most platforms fundamentally can't even construct such an allocation.
1165 /// For instance, no known 64-bit platform can ever serve a request
1166 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1167 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1168 /// more than `isize::MAX` bytes with things like Physical Address
1169 /// Extension. As such, memory acquired directly from allocators or memory
1170 /// mapped files *may* be too large to handle with this function.
1172 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1173 /// difficult to satisfy. The only advantage of this method is that it
1174 /// enables more aggressive compiler optimizations.
1178 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1185 /// #![feature(ptr_offset_from)]
1188 /// let ptr1: *const i32 = &a[1];
1189 /// let ptr2: *const i32 = &a[3];
1191 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1192 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1193 /// assert_eq!(ptr1.offset(2), ptr2);
1194 /// assert_eq!(ptr2.offset(-2), ptr1);
1197 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1199 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1200 let pointee_size = mem::size_of::<T>();
1201 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1203 // This is the same sequence that Clang emits for pointer subtraction.
1204 // It can be neither `nsw` nor `nuw` because the input is treated as
1205 // unsigned but then the output is treated as signed, so neither works.
1206 let d = isize::wrapping_sub(self as _, origin as _);
1207 intrinsics::exact_div(d, pointee_size as _)
1210 /// Calculates the distance between two pointers. The returned value is in
1211 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1213 /// If the address different between the two pointers is not a multiple of
1214 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1217 /// Though this method is safe for any two pointers, note that its result
1218 /// will be mostly useless if the two pointers aren't into the same allocated
1219 /// object, for example if they point to two different local variables.
1223 /// This function panics if `T` is a zero-sized type.
1230 /// #![feature(ptr_wrapping_offset_from)]
1233 /// let ptr1: *const i32 = &a[1];
1234 /// let ptr2: *const i32 = &a[3];
1235 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1236 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1237 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1238 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1240 /// let ptr1: *const i32 = 3 as _;
1241 /// let ptr2: *const i32 = 13 as _;
1242 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1244 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1246 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1247 let pointee_size = mem::size_of::<T>();
1248 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1250 let d = isize::wrapping_sub(self as _, origin as _);
1251 d.wrapping_div(pointee_size as _)
1254 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1256 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1257 /// offset of `3 * size_of::<T>()` bytes.
1261 /// If any of the following conditions are violated, the result is Undefined
1264 /// * Both the starting and resulting pointer must be either in bounds or one
1265 /// byte past the end of the same allocated object.
1267 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1269 /// * The offset being in bounds cannot rely on "wrapping around" the address
1270 /// space. That is, the infinite-precision sum must fit in a `usize`.
1272 /// The compiler and standard library generally tries to ensure allocations
1273 /// never reach a size where an offset is a concern. For instance, `Vec`
1274 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1275 /// `vec.as_ptr().add(vec.len())` is always safe.
1277 /// Most platforms fundamentally can't even construct such an allocation.
1278 /// For instance, no known 64-bit platform can ever serve a request
1279 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1280 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1281 /// more than `isize::MAX` bytes with things like Physical Address
1282 /// Extension. As such, memory acquired directly from allocators or memory
1283 /// mapped files *may* be too large to handle with this function.
1285 /// Consider using `wrapping_offset` instead if these constraints are
1286 /// difficult to satisfy. The only advantage of this method is that it
1287 /// enables more aggressive compiler optimizations.
1294 /// let s: &str = "123";
1295 /// let ptr: *const u8 = s.as_ptr();
1298 /// println!("{}", *ptr.add(1) as char);
1299 /// println!("{}", *ptr.add(2) as char);
1302 #[stable(feature = "pointer_methods", since = "1.26.0")]
1304 pub unsafe fn add(self, count: usize) -> Self
1307 self.offset(count as isize)
1310 /// Calculates the offset from a pointer (convenience for
1311 /// `.offset((count as isize).wrapping_neg())`).
1313 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1314 /// offset of `3 * size_of::<T>()` bytes.
1318 /// If any of the following conditions are violated, the result is Undefined
1321 /// * Both the starting and resulting pointer must be either in bounds or one
1322 /// byte past the end of the same allocated object.
1324 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1326 /// * The offset being in bounds cannot rely on "wrapping around" the address
1327 /// space. That is, the infinite-precision sum must fit in a usize.
1329 /// The compiler and standard library generally tries to ensure allocations
1330 /// never reach a size where an offset is a concern. For instance, `Vec`
1331 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1332 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1334 /// Most platforms fundamentally can't even construct such an allocation.
1335 /// For instance, no known 64-bit platform can ever serve a request
1336 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1337 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1338 /// more than `isize::MAX` bytes with things like Physical Address
1339 /// Extension. As such, memory acquired directly from allocators or memory
1340 /// mapped files *may* be too large to handle with this function.
1342 /// Consider using `wrapping_offset` instead if these constraints are
1343 /// difficult to satisfy. The only advantage of this method is that it
1344 /// enables more aggressive compiler optimizations.
1351 /// let s: &str = "123";
1354 /// let end: *const u8 = s.as_ptr().add(3);
1355 /// println!("{}", *end.sub(1) as char);
1356 /// println!("{}", *end.sub(2) as char);
1359 #[stable(feature = "pointer_methods", since = "1.26.0")]
1361 pub unsafe fn sub(self, count: usize) -> Self
1364 self.offset((count as isize).wrapping_neg())
1367 /// Calculates the offset from a pointer using wrapping arithmetic.
1368 /// (convenience for `.wrapping_offset(count as isize)`)
1370 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1371 /// offset of `3 * size_of::<T>()` bytes.
1375 /// The resulting pointer does not need to be in bounds, but it is
1376 /// potentially hazardous to dereference (which requires `unsafe`).
1378 /// Always use `.add(count)` instead when possible, because `add`
1379 /// allows the compiler to optimize better.
1386 /// // Iterate using a raw pointer in increments of two elements
1387 /// let data = [1u8, 2, 3, 4, 5];
1388 /// let mut ptr: *const u8 = data.as_ptr();
1390 /// let end_rounded_up = ptr.wrapping_add(6);
1392 /// // This loop prints "1, 3, 5, "
1393 /// while ptr != end_rounded_up {
1395 /// print!("{}, ", *ptr);
1397 /// ptr = ptr.wrapping_add(step);
1400 #[stable(feature = "pointer_methods", since = "1.26.0")]
1402 pub fn wrapping_add(self, count: usize) -> Self
1405 self.wrapping_offset(count as isize)
1408 /// Calculates the offset from a pointer using wrapping arithmetic.
1409 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1411 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1412 /// offset of `3 * size_of::<T>()` bytes.
1416 /// The resulting pointer does not need to be in bounds, but it is
1417 /// potentially hazardous to dereference (which requires `unsafe`).
1419 /// Always use `.sub(count)` instead when possible, because `sub`
1420 /// allows the compiler to optimize better.
1427 /// // Iterate using a raw pointer in increments of two elements (backwards)
1428 /// let data = [1u8, 2, 3, 4, 5];
1429 /// let mut ptr: *const u8 = data.as_ptr();
1430 /// let start_rounded_down = ptr.wrapping_sub(2);
1431 /// ptr = ptr.wrapping_add(4);
1433 /// // This loop prints "5, 3, 1, "
1434 /// while ptr != start_rounded_down {
1436 /// print!("{}, ", *ptr);
1438 /// ptr = ptr.wrapping_sub(step);
1441 #[stable(feature = "pointer_methods", since = "1.26.0")]
1443 pub fn wrapping_sub(self, count: usize) -> Self
1446 self.wrapping_offset((count as isize).wrapping_neg())
1449 /// Reads the value from `self` without moving it. This leaves the
1450 /// memory in `self` unchanged.
1452 /// See [`ptr::read`] for safety concerns and examples.
1454 /// [`ptr::read`]: ./ptr/fn.read.html
1455 #[stable(feature = "pointer_methods", since = "1.26.0")]
1457 pub unsafe fn read(self) -> T
1463 /// Performs a volatile read of the value from `self` without moving it. This
1464 /// leaves the memory in `self` unchanged.
1466 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1467 /// to not be elided or reordered by the compiler across other volatile
1470 /// See [`ptr::read_volatile`] for safety concerns and examples.
1472 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
1473 #[stable(feature = "pointer_methods", since = "1.26.0")]
1475 pub unsafe fn read_volatile(self) -> T
1481 /// Reads the value from `self` without moving it. This leaves the
1482 /// memory in `self` unchanged.
1484 /// Unlike `read`, the pointer may be unaligned.
1486 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1488 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
1489 #[stable(feature = "pointer_methods", since = "1.26.0")]
1491 pub unsafe fn read_unaligned(self) -> T
1494 read_unaligned(self)
1497 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1498 /// and destination may overlap.
1500 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1502 /// See [`ptr::copy`] for safety concerns and examples.
1504 /// [`ptr::copy`]: ./ptr/fn.copy.html
1505 #[stable(feature = "pointer_methods", since = "1.26.0")]
1507 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1510 copy(self, dest, count)
1513 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1514 /// and destination may *not* overlap.
1516 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1518 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1520 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
1521 #[stable(feature = "pointer_methods", since = "1.26.0")]
1523 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1526 copy_nonoverlapping(self, dest, count)
1529 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1532 /// If it is not possible to align the pointer, the implementation returns
1533 /// `usize::max_value()`.
1535 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1536 /// used with the `offset` or `offset_to` methods.
1538 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
1539 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1540 /// the returned offset is correct in all terms other than alignment.
1544 /// The function panics if `align` is not a power-of-two.
1548 /// Accessing adjacent `u8` as `u16`
1551 /// # #![feature(align_offset)]
1552 /// # fn foo(n: usize) {
1553 /// # use std::mem::align_of;
1555 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1556 /// let ptr = &x[n] as *const u8;
1557 /// let offset = ptr.align_offset(align_of::<u16>());
1558 /// if offset < x.len() - n - 1 {
1559 /// let u16_ptr = ptr.add(offset) as *const u16;
1560 /// assert_ne!(*u16_ptr, 500);
1562 /// // while the pointer can be aligned via `offset`, it would point
1563 /// // outside the allocation
1567 #[unstable(feature = "align_offset", issue = "44488")]
1568 pub fn align_offset(self, align: usize) -> usize where T: Sized {
1569 if !align.is_power_of_two() {
1570 panic!("align_offset: align is not a power-of-two");
1573 align_offset(self, align)
1580 impl<T: ?Sized> *mut T {
1581 /// Returns `true` if the pointer is null.
1583 /// Note that unsized types have many possible null pointers, as only the
1584 /// raw data pointer is considered, not their length, vtable, etc.
1585 /// Therefore, two pointers that are null may still not compare equal to
1593 /// let mut s = [1, 2, 3];
1594 /// let ptr: *mut u32 = s.as_mut_ptr();
1595 /// assert!(!ptr.is_null());
1597 #[stable(feature = "rust1", since = "1.0.0")]
1599 pub fn is_null(self) -> bool {
1600 // Compare via a cast to a thin pointer, so fat pointers are only
1601 // considering their "data" part for null-ness.
1602 (self as *mut u8) == null_mut()
1605 /// Returns `None` if the pointer is null, or else returns a reference to
1606 /// the value wrapped in `Some`.
1610 /// While this method and its mutable counterpart are useful for
1611 /// null-safety, it is important to note that this is still an unsafe
1612 /// operation because the returned value could be pointing to invalid
1615 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1616 /// not necessarily reflect the actual lifetime of the data.
1623 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1626 /// if let Some(val_back) = ptr.as_ref() {
1627 /// println!("We got back the value: {}!", val_back);
1632 /// # Null-unchecked version
1634 /// If you are sure the pointer can never be null and are looking for some kind of
1635 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1636 /// dereference the pointer directly.
1639 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1642 /// let val_back = &*ptr;
1643 /// println!("We got back the value: {}!", val_back);
1646 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1648 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1656 /// Calculates the offset from a pointer.
1658 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1659 /// offset of `3 * size_of::<T>()` bytes.
1663 /// If any of the following conditions are violated, the result is Undefined
1666 /// * Both the starting and resulting pointer must be either in bounds or one
1667 /// byte past the end of the same allocated object.
1669 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1671 /// * The offset being in bounds cannot rely on "wrapping around" the address
1672 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1674 /// The compiler and standard library generally tries to ensure allocations
1675 /// never reach a size where an offset is a concern. For instance, `Vec`
1676 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1677 /// `vec.as_ptr().add(vec.len())` is always safe.
1679 /// Most platforms fundamentally can't even construct such an allocation.
1680 /// For instance, no known 64-bit platform can ever serve a request
1681 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1682 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1683 /// more than `isize::MAX` bytes with things like Physical Address
1684 /// Extension. As such, memory acquired directly from allocators or memory
1685 /// mapped files *may* be too large to handle with this function.
1687 /// Consider using `wrapping_offset` instead if these constraints are
1688 /// difficult to satisfy. The only advantage of this method is that it
1689 /// enables more aggressive compiler optimizations.
1696 /// let mut s = [1, 2, 3];
1697 /// let ptr: *mut u32 = s.as_mut_ptr();
1700 /// println!("{}", *ptr.offset(1));
1701 /// println!("{}", *ptr.offset(2));
1704 #[stable(feature = "rust1", since = "1.0.0")]
1706 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1707 intrinsics::offset(self, count) as *mut T
1710 /// Calculates the offset from a pointer using wrapping arithmetic.
1711 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1712 /// offset of `3 * size_of::<T>()` bytes.
1716 /// The resulting pointer does not need to be in bounds, but it is
1717 /// potentially hazardous to dereference (which requires `unsafe`).
1718 /// In particular, the resulting pointer may *not* be used to access a
1719 /// different allocated object than the one `self` points to. In other
1720 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1721 /// *not* the same as `y`, and dereferencing it is undefined behavior
1722 /// unless `x` and `y` point into the same allocated object.
1724 /// Always use `.offset(count)` instead when possible, because `offset`
1725 /// allows the compiler to optimize better. If you need to cross object
1726 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1733 /// // Iterate using a raw pointer in increments of two elements
1734 /// let mut data = [1u8, 2, 3, 4, 5];
1735 /// let mut ptr: *mut u8 = data.as_mut_ptr();
1737 /// let end_rounded_up = ptr.wrapping_offset(6);
1739 /// while ptr != end_rounded_up {
1743 /// ptr = ptr.wrapping_offset(step);
1745 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1747 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1749 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1751 intrinsics::arith_offset(self, count) as *mut T
1755 /// Returns `None` if the pointer is null, or else returns a mutable
1756 /// reference to the value wrapped in `Some`.
1760 /// As with `as_ref`, this is unsafe because it cannot verify the validity
1761 /// of the returned pointer, nor can it ensure that the lifetime `'a`
1762 /// returned is indeed a valid lifetime for the contained data.
1769 /// let mut s = [1, 2, 3];
1770 /// let ptr: *mut u32 = s.as_mut_ptr();
1771 /// let first_value = unsafe { ptr.as_mut().unwrap() };
1772 /// *first_value = 4;
1773 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1775 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1777 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1785 /// Calculates the distance between two pointers. The returned value is in
1786 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1788 /// This function is the inverse of [`offset`].
1790 /// [`offset`]: #method.offset-1
1791 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
1795 /// If any of the following conditions are violated, the result is Undefined
1798 /// * Both the starting and other pointer must be either in bounds or one
1799 /// byte past the end of the same allocated object.
1801 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1803 /// * The distance between the pointers, in bytes, must be an exact multiple
1804 /// of the size of `T`.
1806 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1808 /// The compiler and standard library generally try to ensure allocations
1809 /// never reach a size where an offset is a concern. For instance, `Vec`
1810 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1811 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1813 /// Most platforms fundamentally can't even construct such an allocation.
1814 /// For instance, no known 64-bit platform can ever serve a request
1815 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1816 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1817 /// more than `isize::MAX` bytes with things like Physical Address
1818 /// Extension. As such, memory acquired directly from allocators or memory
1819 /// mapped files *may* be too large to handle with this function.
1821 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1822 /// difficult to satisfy. The only advantage of this method is that it
1823 /// enables more aggressive compiler optimizations.
1827 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1834 /// #![feature(ptr_offset_from)]
1836 /// let mut a = [0; 5];
1837 /// let ptr1: *mut i32 = &mut a[1];
1838 /// let ptr2: *mut i32 = &mut a[3];
1840 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1841 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1842 /// assert_eq!(ptr1.offset(2), ptr2);
1843 /// assert_eq!(ptr2.offset(-2), ptr1);
1846 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1848 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1849 (self as *const T).offset_from(origin)
1852 /// Calculates the distance between two pointers. The returned value is in
1853 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1855 /// If the address different between the two pointers is not a multiple of
1856 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1859 /// Though this method is safe for any two pointers, note that its result
1860 /// will be mostly useless if the two pointers aren't into the same allocated
1861 /// object, for example if they point to two different local variables.
1865 /// This function panics if `T` is a zero-sized type.
1872 /// #![feature(ptr_wrapping_offset_from)]
1874 /// let mut a = [0; 5];
1875 /// let ptr1: *mut i32 = &mut a[1];
1876 /// let ptr2: *mut i32 = &mut a[3];
1877 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1878 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1879 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1880 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1882 /// let ptr1: *mut i32 = 3 as _;
1883 /// let ptr2: *mut i32 = 13 as _;
1884 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1886 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1888 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1889 (self as *const T).wrapping_offset_from(origin)
1892 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1894 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1895 /// offset of `3 * size_of::<T>()` bytes.
1899 /// If any of the following conditions are violated, the result is Undefined
1902 /// * Both the starting and resulting pointer must be either in bounds or one
1903 /// byte past the end of the same allocated object.
1905 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1907 /// * The offset being in bounds cannot rely on "wrapping around" the address
1908 /// space. That is, the infinite-precision sum must fit in a `usize`.
1910 /// The compiler and standard library generally tries to ensure allocations
1911 /// never reach a size where an offset is a concern. For instance, `Vec`
1912 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1913 /// `vec.as_ptr().add(vec.len())` is always safe.
1915 /// Most platforms fundamentally can't even construct such an allocation.
1916 /// For instance, no known 64-bit platform can ever serve a request
1917 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1918 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1919 /// more than `isize::MAX` bytes with things like Physical Address
1920 /// Extension. As such, memory acquired directly from allocators or memory
1921 /// mapped files *may* be too large to handle with this function.
1923 /// Consider using `wrapping_offset` instead if these constraints are
1924 /// difficult to satisfy. The only advantage of this method is that it
1925 /// enables more aggressive compiler optimizations.
1932 /// let s: &str = "123";
1933 /// let ptr: *const u8 = s.as_ptr();
1936 /// println!("{}", *ptr.add(1) as char);
1937 /// println!("{}", *ptr.add(2) as char);
1940 #[stable(feature = "pointer_methods", since = "1.26.0")]
1942 pub unsafe fn add(self, count: usize) -> Self
1945 self.offset(count as isize)
1948 /// Calculates the offset from a pointer (convenience for
1949 /// `.offset((count as isize).wrapping_neg())`).
1951 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1952 /// offset of `3 * size_of::<T>()` bytes.
1956 /// If any of the following conditions are violated, the result is Undefined
1959 /// * Both the starting and resulting pointer must be either in bounds or one
1960 /// byte past the end of the same allocated object.
1962 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1964 /// * The offset being in bounds cannot rely on "wrapping around" the address
1965 /// space. That is, the infinite-precision sum must fit in a usize.
1967 /// The compiler and standard library generally tries to ensure allocations
1968 /// never reach a size where an offset is a concern. For instance, `Vec`
1969 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1970 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1972 /// Most platforms fundamentally can't even construct such an allocation.
1973 /// For instance, no known 64-bit platform can ever serve a request
1974 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1975 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1976 /// more than `isize::MAX` bytes with things like Physical Address
1977 /// Extension. As such, memory acquired directly from allocators or memory
1978 /// mapped files *may* be too large to handle with this function.
1980 /// Consider using `wrapping_offset` instead if these constraints are
1981 /// difficult to satisfy. The only advantage of this method is that it
1982 /// enables more aggressive compiler optimizations.
1989 /// let s: &str = "123";
1992 /// let end: *const u8 = s.as_ptr().add(3);
1993 /// println!("{}", *end.sub(1) as char);
1994 /// println!("{}", *end.sub(2) as char);
1997 #[stable(feature = "pointer_methods", since = "1.26.0")]
1999 pub unsafe fn sub(self, count: usize) -> Self
2002 self.offset((count as isize).wrapping_neg())
2005 /// Calculates the offset from a pointer using wrapping arithmetic.
2006 /// (convenience for `.wrapping_offset(count as isize)`)
2008 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
2009 /// offset of `3 * size_of::<T>()` bytes.
2013 /// The resulting pointer does not need to be in bounds, but it is
2014 /// potentially hazardous to dereference (which requires `unsafe`).
2016 /// Always use `.add(count)` instead when possible, because `add`
2017 /// allows the compiler to optimize better.
2024 /// // Iterate using a raw pointer in increments of two elements
2025 /// let data = [1u8, 2, 3, 4, 5];
2026 /// let mut ptr: *const u8 = data.as_ptr();
2028 /// let end_rounded_up = ptr.wrapping_add(6);
2030 /// // This loop prints "1, 3, 5, "
2031 /// while ptr != end_rounded_up {
2033 /// print!("{}, ", *ptr);
2035 /// ptr = ptr.wrapping_add(step);
2038 #[stable(feature = "pointer_methods", since = "1.26.0")]
2040 pub fn wrapping_add(self, count: usize) -> Self
2043 self.wrapping_offset(count as isize)
2046 /// Calculates the offset from a pointer using wrapping arithmetic.
2047 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
2049 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
2050 /// offset of `3 * size_of::<T>()` bytes.
2054 /// The resulting pointer does not need to be in bounds, but it is
2055 /// potentially hazardous to dereference (which requires `unsafe`).
2057 /// Always use `.sub(count)` instead when possible, because `sub`
2058 /// allows the compiler to optimize better.
2065 /// // Iterate using a raw pointer in increments of two elements (backwards)
2066 /// let data = [1u8, 2, 3, 4, 5];
2067 /// let mut ptr: *const u8 = data.as_ptr();
2068 /// let start_rounded_down = ptr.wrapping_sub(2);
2069 /// ptr = ptr.wrapping_add(4);
2071 /// // This loop prints "5, 3, 1, "
2072 /// while ptr != start_rounded_down {
2074 /// print!("{}, ", *ptr);
2076 /// ptr = ptr.wrapping_sub(step);
2079 #[stable(feature = "pointer_methods", since = "1.26.0")]
2081 pub fn wrapping_sub(self, count: usize) -> Self
2084 self.wrapping_offset((count as isize).wrapping_neg())
2087 /// Reads the value from `self` without moving it. This leaves the
2088 /// memory in `self` unchanged.
2090 /// See [`ptr::read`] for safety concerns and examples.
2092 /// [`ptr::read`]: ./ptr/fn.read.html
2093 #[stable(feature = "pointer_methods", since = "1.26.0")]
2095 pub unsafe fn read(self) -> T
2101 /// Performs a volatile read of the value from `self` without moving it. This
2102 /// leaves the memory in `self` unchanged.
2104 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2105 /// to not be elided or reordered by the compiler across other volatile
2108 /// See [`ptr::read_volatile`] for safety concerns and examples.
2110 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
2111 #[stable(feature = "pointer_methods", since = "1.26.0")]
2113 pub unsafe fn read_volatile(self) -> T
2119 /// Reads the value from `self` without moving it. This leaves the
2120 /// memory in `self` unchanged.
2122 /// Unlike `read`, the pointer may be unaligned.
2124 /// See [`ptr::read_unaligned`] for safety concerns and examples.
2126 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
2127 #[stable(feature = "pointer_methods", since = "1.26.0")]
2129 pub unsafe fn read_unaligned(self) -> T
2132 read_unaligned(self)
2135 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2136 /// and destination may overlap.
2138 /// NOTE: this has the *same* argument order as [`ptr::copy`].
2140 /// See [`ptr::copy`] for safety concerns and examples.
2142 /// [`ptr::copy`]: ./ptr/fn.copy.html
2143 #[stable(feature = "pointer_methods", since = "1.26.0")]
2145 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
2148 copy(self, dest, count)
2151 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2152 /// and destination may *not* overlap.
2154 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
2156 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2158 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2159 #[stable(feature = "pointer_methods", since = "1.26.0")]
2161 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
2164 copy_nonoverlapping(self, dest, count)
2167 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2168 /// and destination may overlap.
2170 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
2172 /// See [`ptr::copy`] for safety concerns and examples.
2174 /// [`ptr::copy`]: ./ptr/fn.copy.html
2175 #[stable(feature = "pointer_methods", since = "1.26.0")]
2177 pub unsafe fn copy_from(self, src: *const T, count: usize)
2180 copy(src, self, count)
2183 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2184 /// and destination may *not* overlap.
2186 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
2188 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2190 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2191 #[stable(feature = "pointer_methods", since = "1.26.0")]
2193 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
2196 copy_nonoverlapping(src, self, count)
2199 /// Executes the destructor (if any) of the pointed-to value.
2201 /// See [`ptr::drop_in_place`] for safety concerns and examples.
2203 /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
2204 #[stable(feature = "pointer_methods", since = "1.26.0")]
2206 pub unsafe fn drop_in_place(self) {
2210 /// Overwrites a memory location with the given value without reading or
2211 /// dropping the old value.
2213 /// See [`ptr::write`] for safety concerns and examples.
2215 /// [`ptr::write`]: ./ptr/fn.write.html
2216 #[stable(feature = "pointer_methods", since = "1.26.0")]
2218 pub unsafe fn write(self, val: T)
2224 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
2225 /// bytes of memory starting at `self` to `val`.
2227 /// See [`ptr::write_bytes`] for safety concerns and examples.
2229 /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
2230 #[stable(feature = "pointer_methods", since = "1.26.0")]
2232 pub unsafe fn write_bytes(self, val: u8, count: usize)
2235 write_bytes(self, val, count)
2238 /// Performs a volatile write of a memory location with the given value without
2239 /// reading or dropping the old value.
2241 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2242 /// to not be elided or reordered by the compiler across other volatile
2245 /// See [`ptr::write_volatile`] for safety concerns and examples.
2247 /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
2248 #[stable(feature = "pointer_methods", since = "1.26.0")]
2250 pub unsafe fn write_volatile(self, val: T)
2253 write_volatile(self, val)
2256 /// Overwrites a memory location with the given value without reading or
2257 /// dropping the old value.
2259 /// Unlike `write`, the pointer may be unaligned.
2261 /// See [`ptr::write_unaligned`] for safety concerns and examples.
2263 /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
2264 #[stable(feature = "pointer_methods", since = "1.26.0")]
2266 pub unsafe fn write_unaligned(self, val: T)
2269 write_unaligned(self, val)
2272 /// Replaces the value at `self` with `src`, returning the old
2273 /// value, without dropping either.
2275 /// See [`ptr::replace`] for safety concerns and examples.
2277 /// [`ptr::replace`]: ./ptr/fn.replace.html
2278 #[stable(feature = "pointer_methods", since = "1.26.0")]
2280 pub unsafe fn replace(self, src: T) -> T
2286 /// Swaps the values at two mutable locations of the same type, without
2287 /// deinitializing either. They may overlap, unlike `mem::swap` which is
2288 /// otherwise equivalent.
2290 /// See [`ptr::swap`] for safety concerns and examples.
2292 /// [`ptr::swap`]: ./ptr/fn.swap.html
2293 #[stable(feature = "pointer_methods", since = "1.26.0")]
2295 pub unsafe fn swap(self, with: *mut T)
2301 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
2304 /// If it is not possible to align the pointer, the implementation returns
2305 /// `usize::max_value()`.
2307 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
2308 /// used with the `offset` or `offset_to` methods.
2310 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
2311 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
2312 /// the returned offset is correct in all terms other than alignment.
2316 /// The function panics if `align` is not a power-of-two.
2320 /// Accessing adjacent `u8` as `u16`
2323 /// # #![feature(align_offset)]
2324 /// # fn foo(n: usize) {
2325 /// # use std::mem::align_of;
2327 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
2328 /// let ptr = &x[n] as *const u8;
2329 /// let offset = ptr.align_offset(align_of::<u16>());
2330 /// if offset < x.len() - n - 1 {
2331 /// let u16_ptr = ptr.add(offset) as *const u16;
2332 /// assert_ne!(*u16_ptr, 500);
2334 /// // while the pointer can be aligned via `offset`, it would point
2335 /// // outside the allocation
2339 #[unstable(feature = "align_offset", issue = "44488")]
2340 pub fn align_offset(self, align: usize) -> usize where T: Sized {
2341 if !align.is_power_of_two() {
2342 panic!("align_offset: align is not a power-of-two");
2345 align_offset(self, align)
2350 /// Align pointer `p`.
2352 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
2353 /// to pointer `p` so that pointer `p` would get aligned to `a`.
2355 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
2356 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2359 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2360 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2361 /// than trying to adapt this to accommodate that change.
2363 /// Any questions go to @nagisa.
2364 #[lang="align_offset"]
2365 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2366 /// Calculate multiplicative modular inverse of `x` modulo `m`.
2368 /// This implementation is tailored for align_offset and has following preconditions:
2370 /// * `m` is a power-of-two;
2371 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2373 /// Implementation of this function shall not panic. Ever.
2375 fn mod_inv(x: usize, m: usize) -> usize {
2376 /// Multiplicative modular inverse table modulo 2⁴ = 16.
2378 /// Note, that this table does not contain values where inverse does not exist (i.e. for
2379 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2380 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2381 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2382 const INV_TABLE_MOD: usize = 16;
2384 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
2386 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
2387 if m <= INV_TABLE_MOD {
2388 table_inverse & (m - 1)
2390 // We iterate "up" using the following formula:
2392 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2394 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
2395 let mut inverse = table_inverse;
2396 let mut going_mod = INV_TABLE_MOD_SQUARED;
2398 // y = y * (2 - xy) mod n
2400 // Note, that we use wrapping operations here intentionally – the original formula
2401 // uses e.g. subtraction `mod n`. It is entirely fine to do them `mod
2402 // usize::max_value()` instead, because we take the result `mod n` at the end
2404 inverse = inverse.wrapping_mul(
2405 2usize.wrapping_sub(x.wrapping_mul(inverse))
2406 ) & (going_mod - 1);
2408 return inverse & (m - 1);
2410 going_mod = going_mod.wrapping_mul(going_mod);
2415 let stride = ::mem::size_of::<T>();
2416 let a_minus_one = a.wrapping_sub(1);
2417 let pmoda = p as usize & a_minus_one;
2420 // Already aligned. Yay!
2425 return if stride == 0 {
2426 // If the pointer is not aligned, and the element is zero-sized, then no amount of
2427 // elements will ever align the pointer.
2430 a.wrapping_sub(pmoda)
2434 let smoda = stride & a_minus_one;
2435 // a is power-of-two so cannot be 0. stride = 0 is handled above.
2436 let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
2437 let gcd = 1usize << gcdpow;
2439 if p as usize & (gcd - 1) == 0 {
2440 // This branch solves for the following linear congruence equation:
2442 // $$ p + so ≡ 0 mod a $$
2444 // $p$ here is the pointer value, $s$ – stride of `T`, $o$ offset in `T`s, and $a$ – the
2445 // requested alignment.
2448 // o = (a - (p mod a))/g * ((s/g)⁻¹ mod a)
2450 // The first term is “the relative alignment of p to a”, the second term is “how does
2451 // incrementing p by s bytes change the relative alignment of p”. Division by `g` is
2452 // necessary to make this equation well formed if $a$ and $s$ are not co-prime.
2454 // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
2455 // to take the result $o mod lcm(s, a)$. We can replace $lcm(s, a)$ with just a $a / g$.
2456 let j = a.wrapping_sub(pmoda) >> gcdpow;
2457 let k = smoda >> gcdpow;
2458 return intrinsics::unchecked_rem(j.wrapping_mul(mod_inv(k, a)), a >> gcdpow);
2461 // Cannot be aligned at all.
2467 // Equality for pointers
2468 #[stable(feature = "rust1", since = "1.0.0")]
2469 impl<T: ?Sized> PartialEq for *const T {
2471 fn eq(&self, other: &*const T) -> bool { *self == *other }
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 impl<T: ?Sized> Eq for *const T {}
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 impl<T: ?Sized> PartialEq for *mut T {
2480 fn eq(&self, other: &*mut T) -> bool { *self == *other }
2483 #[stable(feature = "rust1", since = "1.0.0")]
2484 impl<T: ?Sized> Eq for *mut T {}
2486 /// Compare raw pointers for equality.
2488 /// This is the same as using the `==` operator, but less generic:
2489 /// the arguments have to be `*const T` raw pointers,
2490 /// not anything that implements `PartialEq`.
2492 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2493 /// by their address rather than comparing the values they point to
2494 /// (which is what the `PartialEq for &T` implementation does).
2502 /// let other_five = 5;
2503 /// let five_ref = &five;
2504 /// let same_five_ref = &five;
2505 /// let other_five_ref = &other_five;
2507 /// assert!(five_ref == same_five_ref);
2508 /// assert!(five_ref == other_five_ref);
2510 /// assert!(ptr::eq(five_ref, same_five_ref));
2511 /// assert!(!ptr::eq(five_ref, other_five_ref));
2513 #[stable(feature = "ptr_eq", since = "1.17.0")]
2515 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2519 /// Hash the raw pointer address behind a reference, rather than the value
2525 /// #![feature(ptr_hash)]
2526 /// use std::collections::hash_map::DefaultHasher;
2527 /// use std::hash::{Hash, Hasher};
2531 /// let five_ref = &five;
2533 /// let mut hasher = DefaultHasher::new();
2534 /// ptr::hash(five_ref, &mut hasher);
2535 /// let actual = hasher.finish();
2537 /// let mut hasher = DefaultHasher::new();
2538 /// (five_ref as *const i32).hash(&mut hasher);
2539 /// let expected = hasher.finish();
2541 /// assert_eq!(actual, expected);
2543 #[unstable(feature = "ptr_hash", reason = "newly added", issue = "56286")]
2544 pub fn hash<T, S: hash::Hasher>(hashee: *const T, into: &mut S) {
2549 // Impls for function pointers
2550 macro_rules! fnptr_impls_safety_abi {
2551 ($FnTy: ty, $($Arg: ident),*) => {
2552 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2553 impl<Ret, $($Arg),*> PartialEq for $FnTy {
2555 fn eq(&self, other: &Self) -> bool {
2556 *self as usize == *other as usize
2560 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2561 impl<Ret, $($Arg),*> Eq for $FnTy {}
2563 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2564 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2566 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2567 (*self as usize).partial_cmp(&(*other as usize))
2571 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2572 impl<Ret, $($Arg),*> Ord for $FnTy {
2574 fn cmp(&self, other: &Self) -> Ordering {
2575 (*self as usize).cmp(&(*other as usize))
2579 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2580 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2581 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2582 state.write_usize(*self as usize)
2586 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2587 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2588 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2589 fmt::Pointer::fmt(&(*self as *const ()), f)
2593 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2594 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2595 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2596 fmt::Pointer::fmt(&(*self as *const ()), f)
2602 macro_rules! fnptr_impls_args {
2603 ($($Arg: ident),+) => {
2604 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2605 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2606 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2607 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2608 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2609 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2612 // No variadic functions with 0 parameters
2613 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2614 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2615 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2616 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2620 fnptr_impls_args! { }
2621 fnptr_impls_args! { A }
2622 fnptr_impls_args! { A, B }
2623 fnptr_impls_args! { A, B, C }
2624 fnptr_impls_args! { A, B, C, D }
2625 fnptr_impls_args! { A, B, C, D, E }
2626 fnptr_impls_args! { A, B, C, D, E, F }
2627 fnptr_impls_args! { A, B, C, D, E, F, G }
2628 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2629 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2630 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2631 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2632 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2634 // Comparison for pointers
2635 #[stable(feature = "rust1", since = "1.0.0")]
2636 impl<T: ?Sized> Ord for *const T {
2638 fn cmp(&self, other: &*const T) -> Ordering {
2641 } else if self == other {
2649 #[stable(feature = "rust1", since = "1.0.0")]
2650 impl<T: ?Sized> PartialOrd for *const T {
2652 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2653 Some(self.cmp(other))
2657 fn lt(&self, other: &*const T) -> bool { *self < *other }
2660 fn le(&self, other: &*const T) -> bool { *self <= *other }
2663 fn gt(&self, other: &*const T) -> bool { *self > *other }
2666 fn ge(&self, other: &*const T) -> bool { *self >= *other }
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 impl<T: ?Sized> Ord for *mut T {
2672 fn cmp(&self, other: &*mut T) -> Ordering {
2675 } else if self == other {
2683 #[stable(feature = "rust1", since = "1.0.0")]
2684 impl<T: ?Sized> PartialOrd for *mut T {
2686 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2687 Some(self.cmp(other))
2691 fn lt(&self, other: &*mut T) -> bool { *self < *other }
2694 fn le(&self, other: &*mut T) -> bool { *self <= *other }
2697 fn gt(&self, other: &*mut T) -> bool { *self > *other }
2700 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
2703 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
2704 /// of this wrapper owns the referent. Useful for building abstractions like
2705 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
2707 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
2708 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
2709 /// the kind of strong aliasing guarantees an instance of `T` can expect:
2710 /// the referent of the pointer should not be modified without a unique path to
2711 /// its owning Unique.
2713 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
2714 /// consider using `NonNull`, which has weaker semantics.
2716 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2717 /// is never dereferenced. This is so that enums may use this forbidden value
2718 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
2719 /// However the pointer may still dangle if it isn't dereferenced.
2721 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
2722 /// for any type which upholds Unique's aliasing requirements.
2723 #[unstable(feature = "ptr_internals", issue = "0",
2724 reason = "use NonNull instead and consider PhantomData<T> \
2725 (if you also use #[may_dangle]), Send, and/or Sync")]
2727 #[repr(transparent)]
2728 pub struct Unique<T: ?Sized> {
2729 pointer: NonZero<*const T>,
2730 // NOTE: this marker has no consequences for variance, but is necessary
2731 // for dropck to understand that we logically own a `T`.
2733 // For details, see:
2734 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
2735 _marker: PhantomData<T>,
2738 #[unstable(feature = "ptr_internals", issue = "0")]
2739 impl<T: ?Sized> fmt::Debug for Unique<T> {
2740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2741 fmt::Pointer::fmt(&self.as_ptr(), f)
2745 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
2746 /// reference is unaliased. Note that this aliasing invariant is
2747 /// unenforced by the type system; the abstraction using the
2748 /// `Unique` must enforce it.
2749 #[unstable(feature = "ptr_internals", issue = "0")]
2750 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
2752 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
2753 /// reference is unaliased. Note that this aliasing invariant is
2754 /// unenforced by the type system; the abstraction using the
2755 /// `Unique` must enforce it.
2756 #[unstable(feature = "ptr_internals", issue = "0")]
2757 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
2759 #[unstable(feature = "ptr_internals", issue = "0")]
2760 impl<T: Sized> Unique<T> {
2761 /// Creates a new `Unique` that is dangling, but well-aligned.
2763 /// This is useful for initializing types which lazily allocate, like
2764 /// `Vec::new` does.
2766 /// Note that the pointer value may potentially represent a valid pointer to
2767 /// a `T`, which means this must not be used as a "not yet initialized"
2768 /// sentinel value. Types that lazily allocate must track initialization by
2769 /// some other means.
2770 // FIXME: rename to dangling() to match NonNull?
2771 pub const fn empty() -> Self {
2773 Unique::new_unchecked(mem::align_of::<T>() as *mut T)
2778 #[unstable(feature = "ptr_internals", issue = "0")]
2779 impl<T: ?Sized> Unique<T> {
2780 /// Creates a new `Unique`.
2784 /// `ptr` must be non-null.
2785 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2786 Unique { pointer: NonZero(ptr as _), _marker: PhantomData }
2789 /// Creates a new `Unique` if `ptr` is non-null.
2790 pub fn new(ptr: *mut T) -> Option<Self> {
2792 Some(Unique { pointer: unsafe { NonZero(ptr as _) }, _marker: PhantomData })
2798 /// Acquires the underlying `*mut` pointer.
2799 pub fn as_ptr(self) -> *mut T {
2800 self.pointer.0 as *mut T
2803 /// Dereferences the content.
2805 /// The resulting lifetime is bound to self so this behaves "as if"
2806 /// it were actually an instance of T that is getting borrowed. If a longer
2807 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2808 pub unsafe fn as_ref(&self) -> &T {
2812 /// Mutably dereferences the content.
2814 /// The resulting lifetime is bound to self so this behaves "as if"
2815 /// it were actually an instance of T that is getting borrowed. If a longer
2816 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2817 pub unsafe fn as_mut(&mut self) -> &mut T {
2822 #[unstable(feature = "ptr_internals", issue = "0")]
2823 impl<T: ?Sized> Clone for Unique<T> {
2824 fn clone(&self) -> Self {
2829 #[unstable(feature = "ptr_internals", issue = "0")]
2830 impl<T: ?Sized> Copy for Unique<T> { }
2832 #[unstable(feature = "ptr_internals", issue = "0")]
2833 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
2835 #[unstable(feature = "ptr_internals", issue = "0")]
2836 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> { }
2838 #[unstable(feature = "ptr_internals", issue = "0")]
2839 impl<T: ?Sized> fmt::Pointer for Unique<T> {
2840 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2841 fmt::Pointer::fmt(&self.as_ptr(), f)
2845 #[unstable(feature = "ptr_internals", issue = "0")]
2846 impl<'a, T: ?Sized> From<&'a mut T> for Unique<T> {
2847 fn from(reference: &'a mut T) -> Self {
2848 Unique { pointer: unsafe { NonZero(reference as _) }, _marker: PhantomData }
2852 #[unstable(feature = "ptr_internals", issue = "0")]
2853 impl<'a, T: ?Sized> From<&'a T> for Unique<T> {
2854 fn from(reference: &'a T) -> Self {
2855 Unique { pointer: unsafe { NonZero(reference as _) }, _marker: PhantomData }
2859 #[unstable(feature = "ptr_internals", issue = "0")]
2860 impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
2861 fn from(p: NonNull<T>) -> Self {
2862 Unique { pointer: p.pointer, _marker: PhantomData }
2866 /// `*mut T` but non-zero and covariant.
2868 /// This is often the correct thing to use when building data structures using
2869 /// raw pointers, but is ultimately more dangerous to use because of its additional
2870 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
2872 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2873 /// is never dereferenced. This is so that enums may use this forbidden value
2874 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
2875 /// However the pointer may still dangle if it isn't dereferenced.
2877 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
2878 /// for your use case, you should include some PhantomData in your type to
2879 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
2880 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
2881 /// such as Box, Rc, Arc, Vec, and LinkedList. This is the case because they
2882 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
2883 #[stable(feature = "nonnull", since = "1.25.0")]
2884 #[repr(transparent)]
2885 pub struct NonNull<T: ?Sized> {
2886 pointer: NonZero<*const T>,
2889 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
2890 // NB: This impl is unnecessary, but should provide better error messages.
2891 #[stable(feature = "nonnull", since = "1.25.0")]
2892 impl<T: ?Sized> !Send for NonNull<T> { }
2894 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
2895 // NB: This impl is unnecessary, but should provide better error messages.
2896 #[stable(feature = "nonnull", since = "1.25.0")]
2897 impl<T: ?Sized> !Sync for NonNull<T> { }
2899 impl<T: Sized> NonNull<T> {
2900 /// Creates a new `NonNull` that is dangling, but well-aligned.
2902 /// This is useful for initializing types which lazily allocate, like
2903 /// `Vec::new` does.
2905 /// Note that the pointer value may potentially represent a valid pointer to
2906 /// a `T`, which means this must not be used as a "not yet initialized"
2907 /// sentinel value. Types that lazily allocate must track initialization by
2908 /// some other means.
2909 #[stable(feature = "nonnull", since = "1.25.0")]
2911 pub fn dangling() -> Self {
2913 let ptr = mem::align_of::<T>() as *mut T;
2914 NonNull::new_unchecked(ptr)
2919 impl<T: ?Sized> NonNull<T> {
2920 /// Creates a new `NonNull`.
2924 /// `ptr` must be non-null.
2925 #[stable(feature = "nonnull", since = "1.25.0")]
2927 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2928 NonNull { pointer: unsafe { NonZero(ptr as _) } }
2931 /// Creates a new `NonNull` if `ptr` is non-null.
2932 #[stable(feature = "nonnull", since = "1.25.0")]
2934 pub fn new(ptr: *mut T) -> Option<Self> {
2936 Some(unsafe { Self::new_unchecked(ptr) })
2942 /// Acquires the underlying `*mut` pointer.
2943 #[stable(feature = "nonnull", since = "1.25.0")]
2945 pub const fn as_ptr(self) -> *mut T {
2946 self.pointer.0 as *mut T
2949 /// Dereferences the content.
2951 /// The resulting lifetime is bound to self so this behaves "as if"
2952 /// it were actually an instance of T that is getting borrowed. If a longer
2953 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2954 #[stable(feature = "nonnull", since = "1.25.0")]
2956 pub unsafe fn as_ref(&self) -> &T {
2960 /// Mutably dereferences the content.
2962 /// The resulting lifetime is bound to self so this behaves "as if"
2963 /// it were actually an instance of T that is getting borrowed. If a longer
2964 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2965 #[stable(feature = "nonnull", since = "1.25.0")]
2967 pub unsafe fn as_mut(&mut self) -> &mut T {
2971 /// Cast to a pointer of another type
2972 #[stable(feature = "nonnull_cast", since = "1.27.0")]
2974 pub fn cast<U>(self) -> NonNull<U> {
2976 NonNull::new_unchecked(self.as_ptr() as *mut U)
2981 #[stable(feature = "nonnull", since = "1.25.0")]
2982 impl<T: ?Sized> Clone for NonNull<T> {
2983 fn clone(&self) -> Self {
2988 #[stable(feature = "nonnull", since = "1.25.0")]
2989 impl<T: ?Sized> Copy for NonNull<T> { }
2991 #[unstable(feature = "coerce_unsized", issue = "27732")]
2992 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
2994 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
2995 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
2997 #[stable(feature = "nonnull", since = "1.25.0")]
2998 impl<T: ?Sized> fmt::Debug for NonNull<T> {
2999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3000 fmt::Pointer::fmt(&self.as_ptr(), f)
3004 #[stable(feature = "nonnull", since = "1.25.0")]
3005 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
3006 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3007 fmt::Pointer::fmt(&self.as_ptr(), f)
3011 #[stable(feature = "nonnull", since = "1.25.0")]
3012 impl<T: ?Sized> Eq for NonNull<T> {}
3014 #[stable(feature = "nonnull", since = "1.25.0")]
3015 impl<T: ?Sized> PartialEq for NonNull<T> {
3017 fn eq(&self, other: &Self) -> bool {
3018 self.as_ptr() == other.as_ptr()
3022 #[stable(feature = "nonnull", since = "1.25.0")]
3023 impl<T: ?Sized> Ord for NonNull<T> {
3025 fn cmp(&self, other: &Self) -> Ordering {
3026 self.as_ptr().cmp(&other.as_ptr())
3030 #[stable(feature = "nonnull", since = "1.25.0")]
3031 impl<T: ?Sized> PartialOrd for NonNull<T> {
3033 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3034 self.as_ptr().partial_cmp(&other.as_ptr())
3038 #[stable(feature = "nonnull", since = "1.25.0")]
3039 impl<T: ?Sized> hash::Hash for NonNull<T> {
3041 fn hash<H: hash::Hasher>(&self, state: &mut H) {
3042 self.as_ptr().hash(state)
3046 #[unstable(feature = "ptr_internals", issue = "0")]
3047 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
3049 fn from(unique: Unique<T>) -> Self {
3050 NonNull { pointer: unique.pointer }
3054 #[stable(feature = "nonnull", since = "1.25.0")]
3055 impl<'a, T: ?Sized> From<&'a mut T> for NonNull<T> {
3057 fn from(reference: &'a mut T) -> Self {
3058 NonNull { pointer: unsafe { NonZero(reference as _) } }
3062 #[stable(feature = "nonnull", since = "1.25.0")]
3063 impl<'a, T: ?Sized> From<&'a T> for NonNull<T> {
3065 fn from(reference: &'a T) -> Self {
3066 NonNull { pointer: unsafe { NonZero(reference as _) } }