1 // ignore-tidy-filelength
3 //! Manually manage memory through raw pointers.
5 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
9 //! Many functions in this module take raw pointers as arguments and read from
10 //! or write to them. For this to be safe, these pointers must be *valid*.
11 //! Whether a pointer is valid depends on the operation it is used for
12 //! (read or write), and the extent of the memory that is accessed (i.e.,
13 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
14 //! to access only a single value, in which case the documentation omits the size
15 //! and implicitly assumes it to be `size_of::<T>()` bytes.
17 //! The precise rules for validity are not determined yet. The guarantees that are
18 //! provided at this point are very minimal:
20 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
21 //! * All pointers (except for the null pointer) are valid for all operations of
23 //! * All accesses performed by functions in this module are *non-atomic* in the sense
24 //! of [atomic operations] used to synchronize between threads. This means it is
25 //! undefined behavior to perform two concurrent accesses to the same location from different
26 //! threads unless both accesses only read from memory. Notice that this explicitly
27 //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
28 //! be used for inter-thread synchronization.
29 //! * The result of casting a reference to a pointer is valid for as long as the
30 //! underlying object is live and no reference (just raw pointers) is used to
31 //! access the same memory.
33 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
34 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
35 //! will be provided eventually, as the [aliasing] rules are being determined. For more
36 //! information, see the [book] as well as the section in the reference devoted
37 //! to [undefined behavior][ub].
41 //! Valid raw pointers as defined above are not necessarily properly aligned (where
42 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
43 //! aligned to `mem::align_of::<T>()`). However, most functions require their
44 //! arguments to be properly aligned, and will explicitly state
45 //! this requirement in their documentation. Notable exceptions to this are
46 //! [`read_unaligned`] and [`write_unaligned`].
48 //! When a function requires proper alignment, it does so even if the access
49 //! has size 0, i.e., even if memory is not actually touched. Consider using
50 //! [`NonNull::dangling`] in such cases.
52 //! [aliasing]: ../../nomicon/aliasing.html
53 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
54 //! [ub]: ../../reference/behavior-considered-undefined.html
55 //! [null]: ./fn.null.html
56 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
57 //! [atomic operations]: ../../std/sync/atomic/index.html
58 //! [`copy`]: ../../std/ptr/fn.copy.html
59 //! [`offset`]: ../../std/primitive.pointer.html#method.offset
60 //! [`read_unaligned`]: ./fn.read_unaligned.html
61 //! [`write_unaligned`]: ./fn.write_unaligned.html
62 //! [`read_volatile`]: ./fn.read_volatile.html
63 //! [`write_volatile`]: ./fn.write_volatile.html
64 //! [`NonNull::dangling`]: ./struct.NonNull.html#method.dangling
66 #![stable(feature = "rust1", since = "1.0.0")]
68 use crate::convert::From;
69 use crate::intrinsics;
70 use crate::ops::{CoerceUnsized, DispatchFromDyn};
73 use crate::marker::{PhantomData, Unsize};
74 use crate::mem::{self, MaybeUninit};
76 use crate::cmp::Ordering::{self, Less, Equal, Greater};
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use crate::intrinsics::copy_nonoverlapping;
81 #[stable(feature = "rust1", since = "1.0.0")]
82 pub use crate::intrinsics::copy;
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub use crate::intrinsics::write_bytes;
87 /// Executes the destructor (if any) of the pointed-to value.
89 /// This is semantically equivalent to calling [`ptr::read`] and discarding
90 /// the result, but has the following advantages:
92 /// * It is *required* to use `drop_in_place` to drop unsized types like
93 /// trait objects, because they can't be read out onto the stack and
96 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
97 /// dropping manually allocated memory (e.g., when writing Box/Rc/Vec),
98 /// as the compiler doesn't need to prove that it's sound to elide the
101 /// [`ptr::read`]: ../ptr/fn.read.html
105 /// Behavior is undefined if any of the following conditions are violated:
107 /// * `to_drop` must be [valid] for reads.
109 /// * `to_drop` must be properly aligned. See the example below for how to drop
110 /// an unaligned pointer.
112 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
113 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
114 /// foo` counts as a use because it will cause the value to be dropped
115 /// again. [`write`] can be used to overwrite data without causing it to be
118 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
120 /// [valid]: ../ptr/index.html#safety
121 /// [`Copy`]: ../marker/trait.Copy.html
122 /// [`write`]: ../ptr/fn.write.html
126 /// Manually remove the last item from a vector:
132 /// let last = Rc::new(1);
133 /// let weak = Rc::downgrade(&last);
135 /// let mut v = vec![Rc::new(0), last];
138 /// // Get a raw pointer to the last element in `v`.
139 /// let ptr = &mut v[1] as *mut _;
140 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
141 /// // to prevent issues if the `drop_in_place` below panics.
143 /// // Without a call `drop_in_place`, the last item would never be dropped,
144 /// // and the memory it manages would be leaked.
145 /// ptr::drop_in_place(ptr);
148 /// assert_eq!(v, &[0.into()]);
150 /// // Ensure that the last item was dropped.
151 /// assert!(weak.upgrade().is_none());
154 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
158 /// use std::mem::{self, MaybeUninit};
160 /// unsafe fn drop_after_copy<T>(to_drop: *mut T) {
161 /// let mut copy: MaybeUninit<T> = MaybeUninit::uninit();
162 /// ptr::copy(to_drop, copy.as_mut_ptr(), 1);
163 /// drop(copy.assume_init());
166 /// #[repr(packed, C)]
169 /// unaligned: Vec<i32>,
172 /// let mut p = Packed { _padding: 0, unaligned: vec![42] };
174 /// drop_after_copy(&mut p.unaligned as *mut _);
179 /// Notice that the compiler performs this copy automatically when dropping packed structs,
180 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
182 #[stable(feature = "drop_in_place", since = "1.8.0")]
184 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
185 real_drop_in_place(&mut *to_drop)
188 // The real `drop_in_place` -- the one that gets called implicitly when variables go
189 // out of scope -- should have a safe reference and not a raw pointer as argument
190 // type. When we drop a local variable, we access it with a pointer that behaves
191 // like a safe reference; transmuting that to a raw pointer does not mean we can
192 // actually access it with raw pointers.
193 #[lang = "drop_in_place"]
194 #[allow(unconditional_recursion)]
195 unsafe fn real_drop_in_place<T: ?Sized>(to_drop: &mut T) {
196 // Code here does not matter - this is replaced by the
197 // real drop glue by the compiler.
198 real_drop_in_place(to_drop)
201 /// Creates a null raw pointer.
208 /// let p: *const i32 = ptr::null();
209 /// assert!(p.is_null());
212 #[stable(feature = "rust1", since = "1.0.0")]
214 pub const fn null<T>() -> *const T { 0 as *const T }
216 /// Creates a null mutable raw pointer.
223 /// let p: *mut i32 = ptr::null_mut();
224 /// assert!(p.is_null());
227 #[stable(feature = "rust1", since = "1.0.0")]
229 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
231 /// Swaps the values at two mutable locations of the same type, without
232 /// deinitializing either.
234 /// But for the following two exceptions, this function is semantically
235 /// equivalent to [`mem::swap`]:
237 /// * It operates on raw pointers instead of references. When references are
238 /// available, [`mem::swap`] should be preferred.
240 /// * The two pointed-to values may overlap. If the values do overlap, then the
241 /// overlapping region of memory from `x` will be used. This is demonstrated
242 /// in the second example below.
244 /// [`mem::swap`]: ../mem/fn.swap.html
248 /// Behavior is undefined if any of the following conditions are violated:
250 /// * Both `x` and `y` must be [valid] for reads and writes.
252 /// * Both `x` and `y` must be properly aligned.
254 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
256 /// [valid]: ../ptr/index.html#safety
260 /// Swapping two non-overlapping regions:
265 /// let mut array = [0, 1, 2, 3];
267 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
268 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
272 /// assert_eq!([2, 3, 0, 1], array);
276 /// Swapping two overlapping regions:
281 /// let mut array = [0, 1, 2, 3];
283 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
284 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
288 /// // The indices `1..3` of the slice overlap between `x` and `y`.
289 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
290 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
291 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
292 /// // This implementation is defined to make the latter choice.
293 /// assert_eq!([1, 0, 1, 2], array);
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
299 // Give ourselves some scratch space to work with.
300 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
301 let mut tmp = MaybeUninit::<T>::uninit();
304 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
305 copy(y, x, 1); // `x` and `y` may overlap
306 copy_nonoverlapping(tmp.as_ptr(), y, 1);
309 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
310 /// beginning at `x` and `y`. The two regions must *not* overlap.
314 /// Behavior is undefined if any of the following conditions are violated:
316 /// * Both `x` and `y` must be [valid] for reads and writes of `count *
317 /// size_of::<T>()` bytes.
319 /// * Both `x` and `y` must be properly aligned.
321 /// * The region of memory beginning at `x` with a size of `count *
322 /// size_of::<T>()` bytes must *not* overlap with the region of memory
323 /// beginning at `y` with the same size.
325 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
326 /// the pointers must be non-NULL and properly aligned.
328 /// [valid]: ../ptr/index.html#safety
337 /// let mut x = [1, 2, 3, 4];
338 /// let mut y = [7, 8, 9];
341 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
344 /// assert_eq!(x, [7, 8, 3, 4]);
345 /// assert_eq!(y, [1, 2, 9]);
348 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
349 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
350 let x = x as *mut u8;
351 let y = y as *mut u8;
352 let len = mem::size_of::<T>() * count;
353 swap_nonoverlapping_bytes(x, y, len)
357 pub(crate) unsafe fn swap_nonoverlapping_one<T>(x: *mut T, y: *mut T) {
358 // For types smaller than the block optimization below,
359 // just swap directly to avoid pessimizing codegen.
360 if mem::size_of::<T>() < 32 {
362 copy_nonoverlapping(y, x, 1);
365 swap_nonoverlapping(x, y, 1);
370 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
371 // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
372 // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
373 // Haswell E processors. LLVM is more able to optimize if we give a struct a
374 // #[repr(simd)], even if we don't actually use this struct directly.
376 // FIXME repr(simd) broken on emscripten and redox
377 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))]
378 struct Block(u64, u64, u64, u64);
379 struct UnalignedBlock(u64, u64, u64, u64);
381 let block_size = mem::size_of::<Block>();
383 // Loop through x & y, copying them `Block` at a time
384 // The optimizer should unroll the loop fully for most types
385 // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
387 while i + block_size <= len {
388 // Create some uninitialized memory as scratch space
389 // Declaring `t` here avoids aligning the stack when this loop is unused
390 let mut t = mem::MaybeUninit::<Block>::uninit();
391 let t = t.as_mut_ptr() as *mut u8;
395 // Swap a block of bytes of x & y, using t as a temporary buffer
396 // This should be optimized into efficient SIMD operations where available
397 copy_nonoverlapping(x, t, block_size);
398 copy_nonoverlapping(y, x, block_size);
399 copy_nonoverlapping(t, y, block_size);
404 // Swap any remaining bytes
405 let mut t = mem::MaybeUninit::<UnalignedBlock>::uninit();
408 let t = t.as_mut_ptr() as *mut u8;
412 copy_nonoverlapping(x, t, rem);
413 copy_nonoverlapping(y, x, rem);
414 copy_nonoverlapping(t, y, rem);
418 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
420 /// Neither value is dropped.
422 /// This function is semantically equivalent to [`mem::replace`] except that it
423 /// operates on raw pointers instead of references. When references are
424 /// available, [`mem::replace`] should be preferred.
426 /// [`mem::replace`]: ../mem/fn.replace.html
430 /// Behavior is undefined if any of the following conditions are violated:
432 /// * `dst` must be [valid] for writes.
434 /// * `dst` must be properly aligned.
436 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
438 /// [valid]: ../ptr/index.html#safety
445 /// let mut rust = vec!['b', 'u', 's', 't'];
447 /// // `mem::replace` would have the same effect without requiring the unsafe
450 /// ptr::replace(&mut rust[0], 'r')
453 /// assert_eq!(b, 'b');
454 /// assert_eq!(rust, &['r', 'u', 's', 't']);
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
459 mem::swap(&mut *dst, &mut src); // cannot overlap
463 /// Reads the value from `src` without moving it. This leaves the
464 /// memory in `src` unchanged.
468 /// Behavior is undefined if any of the following conditions are violated:
470 /// * `src` must be [valid] for reads.
472 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
475 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
483 /// let y = &x as *const i32;
486 /// assert_eq!(std::ptr::read(y), 12);
490 /// Manually implement [`mem::swap`]:
495 /// fn swap<T>(a: &mut T, b: &mut T) {
497 /// // Create a bitwise copy of the value at `a` in `tmp`.
498 /// let tmp = ptr::read(a);
500 /// // Exiting at this point (either by explicitly returning or by
501 /// // calling a function which panics) would cause the value in `tmp` to
502 /// // be dropped while the same value is still referenced by `a`. This
503 /// // could trigger undefined behavior if `T` is not `Copy`.
505 /// // Create a bitwise copy of the value at `b` in `a`.
506 /// // This is safe because mutable references cannot alias.
507 /// ptr::copy_nonoverlapping(b, a, 1);
509 /// // As above, exiting here could trigger undefined behavior because
510 /// // the same value is referenced by `a` and `b`.
512 /// // Move `tmp` into `b`.
513 /// ptr::write(b, tmp);
515 /// // `tmp` has been moved (`write` takes ownership of its second argument),
516 /// // so nothing is dropped implicitly here.
520 /// let mut foo = "foo".to_owned();
521 /// let mut bar = "bar".to_owned();
523 /// swap(&mut foo, &mut bar);
525 /// assert_eq!(foo, "bar");
526 /// assert_eq!(bar, "foo");
529 /// ## Ownership of the Returned Value
531 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
532 /// If `T` is not [`Copy`], using both the returned value and the value at
533 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
534 /// use because it will attempt to drop the value at `*src`.
536 /// [`write`] can be used to overwrite data without causing it to be dropped.
541 /// let mut s = String::from("foo");
543 /// // `s2` now points to the same underlying memory as `s`.
544 /// let mut s2: String = ptr::read(&s);
546 /// assert_eq!(s2, "foo");
548 /// // Assigning to `s2` causes its original value to be dropped. Beyond
549 /// // this point, `s` must no longer be used, as the underlying memory has
551 /// s2 = String::default();
552 /// assert_eq!(s2, "");
554 /// // Assigning to `s` would cause the old value to be dropped again,
555 /// // resulting in undefined behavior.
556 /// // s = String::from("bar"); // ERROR
558 /// // `ptr::write` can be used to overwrite a value without dropping it.
559 /// ptr::write(&mut s, String::from("bar"));
562 /// assert_eq!(s, "bar");
565 /// [`mem::swap`]: ../mem/fn.swap.html
566 /// [valid]: ../ptr/index.html#safety
567 /// [`Copy`]: ../marker/trait.Copy.html
568 /// [`read_unaligned`]: ./fn.read_unaligned.html
569 /// [`write`]: ./fn.write.html
571 #[stable(feature = "rust1", since = "1.0.0")]
572 pub unsafe fn read<T>(src: *const T) -> T {
573 let mut tmp = MaybeUninit::<T>::uninit();
574 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
578 /// Reads the value from `src` without moving it. This leaves the
579 /// memory in `src` unchanged.
581 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
585 /// Behavior is undefined if any of the following conditions are violated:
587 /// * `src` must be [valid] for reads.
589 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
590 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
591 /// value and the value at `*src` can [violate memory safety][read-ownership].
593 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
595 /// [`Copy`]: ../marker/trait.Copy.html
596 /// [`read`]: ./fn.read.html
597 /// [`write_unaligned`]: ./fn.write_unaligned.html
598 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
599 /// [valid]: ../ptr/index.html#safety
603 /// Access members of a packed struct by reference:
608 /// #[repr(packed, C)]
616 /// unaligned: 0x01020304,
620 /// // Take the address of a 32-bit integer which is not aligned.
621 /// // This must be done as a raw pointer; unaligned references are invalid.
622 /// let unaligned = &x.unaligned as *const u32;
624 /// // Dereferencing normally will emit an aligned load instruction,
625 /// // causing undefined behavior.
626 /// // let v = *unaligned; // ERROR
628 /// // Instead, use `read_unaligned` to read improperly aligned values.
629 /// let v = ptr::read_unaligned(unaligned);
634 /// // Accessing unaligned values directly is safe.
635 /// assert!(x.unaligned == v);
638 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
639 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
640 let mut tmp = MaybeUninit::<T>::uninit();
641 copy_nonoverlapping(src as *const u8,
642 tmp.as_mut_ptr() as *mut u8,
643 mem::size_of::<T>());
647 /// Overwrites a memory location with the given value without reading or
648 /// dropping the old value.
650 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
651 /// allocations or resources, so care should be taken not to overwrite an object
652 /// that should be dropped.
654 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
655 /// location pointed to by `dst`.
657 /// This is appropriate for initializing uninitialized memory, or overwriting
658 /// memory that has previously been [`read`] from.
660 /// [`read`]: ./fn.read.html
664 /// Behavior is undefined if any of the following conditions are violated:
666 /// * `dst` must be [valid] for writes.
668 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
671 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
673 /// [valid]: ../ptr/index.html#safety
674 /// [`write_unaligned`]: ./fn.write_unaligned.html
682 /// let y = &mut x as *mut i32;
686 /// std::ptr::write(y, z);
687 /// assert_eq!(std::ptr::read(y), 12);
691 /// Manually implement [`mem::swap`]:
696 /// fn swap<T>(a: &mut T, b: &mut T) {
698 /// // Create a bitwise copy of the value at `a` in `tmp`.
699 /// let tmp = ptr::read(a);
701 /// // Exiting at this point (either by explicitly returning or by
702 /// // calling a function which panics) would cause the value in `tmp` to
703 /// // be dropped while the same value is still referenced by `a`. This
704 /// // could trigger undefined behavior if `T` is not `Copy`.
706 /// // Create a bitwise copy of the value at `b` in `a`.
707 /// // This is safe because mutable references cannot alias.
708 /// ptr::copy_nonoverlapping(b, a, 1);
710 /// // As above, exiting here could trigger undefined behavior because
711 /// // the same value is referenced by `a` and `b`.
713 /// // Move `tmp` into `b`.
714 /// ptr::write(b, tmp);
716 /// // `tmp` has been moved (`write` takes ownership of its second argument),
717 /// // so nothing is dropped implicitly here.
721 /// let mut foo = "foo".to_owned();
722 /// let mut bar = "bar".to_owned();
724 /// swap(&mut foo, &mut bar);
726 /// assert_eq!(foo, "bar");
727 /// assert_eq!(bar, "foo");
730 /// [`mem::swap`]: ../mem/fn.swap.html
732 #[stable(feature = "rust1", since = "1.0.0")]
733 pub unsafe fn write<T>(dst: *mut T, src: T) {
734 intrinsics::move_val_init(&mut *dst, src)
737 /// Overwrites a memory location with the given value without reading or
738 /// dropping the old value.
740 /// Unlike [`write`], the pointer may be unaligned.
742 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
743 /// could leak allocations or resources, so care should be taken not to overwrite
744 /// an object that should be dropped.
746 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
747 /// location pointed to by `dst`.
749 /// This is appropriate for initializing uninitialized memory, or overwriting
750 /// memory that has previously been read with [`read_unaligned`].
752 /// [`write`]: ./fn.write.html
753 /// [`read_unaligned`]: ./fn.read_unaligned.html
757 /// Behavior is undefined if any of the following conditions are violated:
759 /// * `dst` must be [valid] for writes.
761 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
763 /// [valid]: ../ptr/index.html#safety
767 /// Access fields in a packed struct:
770 /// use std::{mem, ptr};
772 /// #[repr(packed, C)]
773 /// #[derive(Default)]
779 /// let v = 0x01020304;
780 /// let mut x: Packed = unsafe { mem::zeroed() };
783 /// // Take a reference to a 32-bit integer which is not aligned.
784 /// let unaligned = &mut x.unaligned as *mut u32;
786 /// // Dereferencing normally will emit an aligned store instruction,
787 /// // causing undefined behavior because the pointer is not aligned.
788 /// // *unaligned = v; // ERROR
790 /// // Instead, use `write_unaligned` to write improperly aligned values.
791 /// ptr::write_unaligned(unaligned, v);
794 /// // Accessing unaligned values directly is safe.
795 /// assert!(x.unaligned == v);
798 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
799 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
800 copy_nonoverlapping(&src as *const T as *const u8,
802 mem::size_of::<T>());
806 /// Performs a volatile read of the value from `src` without moving it. This
807 /// leaves the memory in `src` unchanged.
809 /// Volatile operations are intended to act on I/O memory, and are guaranteed
810 /// to not be elided or reordered by the compiler across other volatile
813 /// Memory accessed with `read_volatile` or [`write_volatile`] should not be
814 /// accessed with non-volatile operations.
816 /// [`write_volatile`]: ./fn.write_volatile.html
820 /// Rust does not currently have a rigorously and formally defined memory model,
821 /// so the precise semantics of what "volatile" means here is subject to change
822 /// over time. That being said, the semantics will almost always end up pretty
823 /// similar to [C11's definition of volatile][c11].
825 /// The compiler shouldn't change the relative order or number of volatile
826 /// memory operations. However, volatile memory operations on zero-sized types
827 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
828 /// and may be ignored.
830 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
834 /// Behavior is undefined if any of the following conditions are violated:
836 /// * `src` must be [valid] for reads.
838 /// * `src` must be properly aligned.
840 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
841 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
842 /// value and the value at `*src` can [violate memory safety][read-ownership].
843 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
846 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
848 /// [valid]: ../ptr/index.html#safety
849 /// [`Copy`]: ../marker/trait.Copy.html
850 /// [`read`]: ./fn.read.html
851 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
853 /// Just like in C, whether an operation is volatile has no bearing whatsoever
854 /// on questions involving concurrent access from multiple threads. Volatile
855 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
856 /// a race between a `read_volatile` and any write operation to the same location
857 /// is undefined behavior.
865 /// let y = &x as *const i32;
868 /// assert_eq!(std::ptr::read_volatile(y), 12);
872 #[stable(feature = "volatile", since = "1.9.0")]
873 pub unsafe fn read_volatile<T>(src: *const T) -> T {
874 intrinsics::volatile_load(src)
877 /// Performs a volatile write of a memory location with the given value without
878 /// reading or dropping the old value.
880 /// Volatile operations are intended to act on I/O memory, and are guaranteed
881 /// to not be elided or reordered by the compiler across other volatile
884 /// Memory accessed with [`read_volatile`] or `write_volatile` should not be
885 /// accessed with non-volatile operations.
887 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
888 /// could leak allocations or resources, so care should be taken not to overwrite
889 /// an object that should be dropped.
891 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
892 /// location pointed to by `dst`.
894 /// [`read_volatile`]: ./fn.read_volatile.html
898 /// Rust does not currently have a rigorously and formally defined memory model,
899 /// so the precise semantics of what "volatile" means here is subject to change
900 /// over time. That being said, the semantics will almost always end up pretty
901 /// similar to [C11's definition of volatile][c11].
903 /// The compiler shouldn't change the relative order or number of volatile
904 /// memory operations. However, volatile memory operations on zero-sized types
905 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
906 /// and may be ignored.
908 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
912 /// Behavior is undefined if any of the following conditions are violated:
914 /// * `dst` must be [valid] for writes.
916 /// * `dst` must be properly aligned.
918 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
920 /// [valid]: ../ptr/index.html#safety
922 /// Just like in C, whether an operation is volatile has no bearing whatsoever
923 /// on questions involving concurrent access from multiple threads. Volatile
924 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
925 /// a race between a `write_volatile` and any other operation (reading or writing)
926 /// on the same location is undefined behavior.
934 /// let y = &mut x as *mut i32;
938 /// std::ptr::write_volatile(y, z);
939 /// assert_eq!(std::ptr::read_volatile(y), 12);
943 #[stable(feature = "volatile", since = "1.9.0")]
944 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
945 intrinsics::volatile_store(dst, src);
948 #[lang = "const_ptr"]
949 impl<T: ?Sized> *const T {
950 /// Returns `true` if the pointer is null.
952 /// Note that unsized types have many possible null pointers, as only the
953 /// raw data pointer is considered, not their length, vtable, etc.
954 /// Therefore, two pointers that are null may still not compare equal to
962 /// let s: &str = "Follow the rabbit";
963 /// let ptr: *const u8 = s.as_ptr();
964 /// assert!(!ptr.is_null());
966 #[stable(feature = "rust1", since = "1.0.0")]
968 pub fn is_null(self) -> bool {
969 // Compare via a cast to a thin pointer, so fat pointers are only
970 // considering their "data" part for null-ness.
971 (self as *const u8) == null()
974 /// Cast to a pointer to a different type
975 #[unstable(feature = "ptr_cast", issue = "60602")]
977 pub const fn cast<U>(self) -> *const U {
981 /// Returns `None` if the pointer is null, or else returns a reference to
982 /// the value wrapped in `Some`.
986 /// While this method and its mutable counterpart are useful for
987 /// null-safety, it is important to note that this is still an unsafe
988 /// operation because the returned value could be pointing to invalid
991 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
992 /// not necessarily reflect the actual lifetime of the data.
999 /// let ptr: *const u8 = &10u8 as *const u8;
1002 /// if let Some(val_back) = ptr.as_ref() {
1003 /// println!("We got back the value: {}!", val_back);
1008 /// # Null-unchecked version
1010 /// If you are sure the pointer can never be null and are looking for some kind of
1011 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1012 /// dereference the pointer directly.
1015 /// let ptr: *const u8 = &10u8 as *const u8;
1018 /// let val_back = &*ptr;
1019 /// println!("We got back the value: {}!", val_back);
1022 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1024 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1032 /// Calculates the offset from a pointer.
1034 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1035 /// offset of `3 * size_of::<T>()` bytes.
1039 /// If any of the following conditions are violated, the result is Undefined
1042 /// * Both the starting and resulting pointer must be either in bounds or one
1043 /// byte past the end of the same allocated object.
1045 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1047 /// * The offset being in bounds cannot rely on "wrapping around" the address
1048 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1050 /// The compiler and standard library generally tries to ensure allocations
1051 /// never reach a size where an offset is a concern. For instance, `Vec`
1052 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1053 /// `vec.as_ptr().add(vec.len())` is always safe.
1055 /// Most platforms fundamentally can't even construct such an allocation.
1056 /// For instance, no known 64-bit platform can ever serve a request
1057 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1058 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1059 /// more than `isize::MAX` bytes with things like Physical Address
1060 /// Extension. As such, memory acquired directly from allocators or memory
1061 /// mapped files *may* be too large to handle with this function.
1063 /// Consider using `wrapping_offset` instead if these constraints are
1064 /// difficult to satisfy. The only advantage of this method is that it
1065 /// enables more aggressive compiler optimizations.
1072 /// let s: &str = "123";
1073 /// let ptr: *const u8 = s.as_ptr();
1076 /// println!("{}", *ptr.offset(1) as char);
1077 /// println!("{}", *ptr.offset(2) as char);
1080 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
1083 intrinsics::offset(self, count)
1086 /// Calculates the offset from a pointer using wrapping arithmetic.
1088 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1089 /// offset of `3 * size_of::<T>()` bytes.
1093 /// The resulting pointer does not need to be in bounds, but it is
1094 /// potentially hazardous to dereference (which requires `unsafe`).
1095 /// In particular, the resulting pointer may *not* be used to access a
1096 /// different allocated object than the one `self` points to. In other
1097 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1098 /// *not* the same as `y`, and dereferencing it is undefined behavior
1099 /// unless `x` and `y` point into the same allocated object.
1101 /// Always use `.offset(count)` instead when possible, because `offset`
1102 /// allows the compiler to optimize better. If you need to cross object
1103 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1110 /// // Iterate using a raw pointer in increments of two elements
1111 /// let data = [1u8, 2, 3, 4, 5];
1112 /// let mut ptr: *const u8 = data.as_ptr();
1114 /// let end_rounded_up = ptr.wrapping_offset(6);
1116 /// // This loop prints "1, 3, 5, "
1117 /// while ptr != end_rounded_up {
1119 /// print!("{}, ", *ptr);
1121 /// ptr = ptr.wrapping_offset(step);
1124 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1126 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
1128 intrinsics::arith_offset(self, count)
1132 /// Calculates the distance between two pointers. The returned value is in
1133 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1135 /// This function is the inverse of [`offset`].
1137 /// [`offset`]: #method.offset
1138 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
1142 /// If any of the following conditions are violated, the result is Undefined
1145 /// * Both the starting and other pointer must be either in bounds or one
1146 /// byte past the end of the same allocated object.
1148 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1150 /// * The distance between the pointers, in bytes, must be an exact multiple
1151 /// of the size of `T`.
1153 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1155 /// The compiler and standard library generally try to ensure allocations
1156 /// never reach a size where an offset is a concern. For instance, `Vec`
1157 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1158 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1160 /// Most platforms fundamentally can't even construct such an allocation.
1161 /// For instance, no known 64-bit platform can ever serve a request
1162 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1163 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1164 /// more than `isize::MAX` bytes with things like Physical Address
1165 /// Extension. As such, memory acquired directly from allocators or memory
1166 /// mapped files *may* be too large to handle with this function.
1168 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1169 /// difficult to satisfy. The only advantage of this method is that it
1170 /// enables more aggressive compiler optimizations.
1174 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1181 /// #![feature(ptr_offset_from)]
1184 /// let ptr1: *const i32 = &a[1];
1185 /// let ptr2: *const i32 = &a[3];
1187 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1188 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1189 /// assert_eq!(ptr1.offset(2), ptr2);
1190 /// assert_eq!(ptr2.offset(-2), ptr1);
1193 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1195 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1196 let pointee_size = mem::size_of::<T>();
1197 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1199 // This is the same sequence that Clang emits for pointer subtraction.
1200 // It can be neither `nsw` nor `nuw` because the input is treated as
1201 // unsigned but then the output is treated as signed, so neither works.
1202 let d = isize::wrapping_sub(self as _, origin as _);
1203 intrinsics::exact_div(d, pointee_size as _)
1206 /// Calculates the distance between two pointers. The returned value is in
1207 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1209 /// If the address different between the two pointers is not a multiple of
1210 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1213 /// Though this method is safe for any two pointers, note that its result
1214 /// will be mostly useless if the two pointers aren't into the same allocated
1215 /// object, for example if they point to two different local variables.
1219 /// This function panics if `T` is a zero-sized type.
1226 /// #![feature(ptr_wrapping_offset_from)]
1229 /// let ptr1: *const i32 = &a[1];
1230 /// let ptr2: *const i32 = &a[3];
1231 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1232 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1233 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1234 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1236 /// let ptr1: *const i32 = 3 as _;
1237 /// let ptr2: *const i32 = 13 as _;
1238 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1240 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1242 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1243 let pointee_size = mem::size_of::<T>();
1244 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1246 let d = isize::wrapping_sub(self as _, origin as _);
1247 d.wrapping_div(pointee_size as _)
1250 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1252 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1253 /// offset of `3 * size_of::<T>()` bytes.
1257 /// If any of the following conditions are violated, the result is Undefined
1260 /// * Both the starting and resulting pointer must be either in bounds or one
1261 /// byte past the end of the same allocated object.
1263 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1265 /// * The offset being in bounds cannot rely on "wrapping around" the address
1266 /// space. That is, the infinite-precision sum must fit in a `usize`.
1268 /// The compiler and standard library generally tries to ensure allocations
1269 /// never reach a size where an offset is a concern. For instance, `Vec`
1270 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1271 /// `vec.as_ptr().add(vec.len())` is always safe.
1273 /// Most platforms fundamentally can't even construct such an allocation.
1274 /// For instance, no known 64-bit platform can ever serve a request
1275 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1276 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1277 /// more than `isize::MAX` bytes with things like Physical Address
1278 /// Extension. As such, memory acquired directly from allocators or memory
1279 /// mapped files *may* be too large to handle with this function.
1281 /// Consider using `wrapping_offset` instead if these constraints are
1282 /// difficult to satisfy. The only advantage of this method is that it
1283 /// enables more aggressive compiler optimizations.
1290 /// let s: &str = "123";
1291 /// let ptr: *const u8 = s.as_ptr();
1294 /// println!("{}", *ptr.add(1) as char);
1295 /// println!("{}", *ptr.add(2) as char);
1298 #[stable(feature = "pointer_methods", since = "1.26.0")]
1300 pub unsafe fn add(self, count: usize) -> Self
1303 self.offset(count as isize)
1306 /// Calculates the offset from a pointer (convenience for
1307 /// `.offset((count as isize).wrapping_neg())`).
1309 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1310 /// offset of `3 * size_of::<T>()` bytes.
1314 /// If any of the following conditions are violated, the result is Undefined
1317 /// * Both the starting and resulting pointer must be either in bounds or one
1318 /// byte past the end of the same allocated object.
1320 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1322 /// * The offset being in bounds cannot rely on "wrapping around" the address
1323 /// space. That is, the infinite-precision sum must fit in a usize.
1325 /// The compiler and standard library generally tries to ensure allocations
1326 /// never reach a size where an offset is a concern. For instance, `Vec`
1327 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1328 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1330 /// Most platforms fundamentally can't even construct such an allocation.
1331 /// For instance, no known 64-bit platform can ever serve a request
1332 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1333 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1334 /// more than `isize::MAX` bytes with things like Physical Address
1335 /// Extension. As such, memory acquired directly from allocators or memory
1336 /// mapped files *may* be too large to handle with this function.
1338 /// Consider using `wrapping_offset` instead if these constraints are
1339 /// difficult to satisfy. The only advantage of this method is that it
1340 /// enables more aggressive compiler optimizations.
1347 /// let s: &str = "123";
1350 /// let end: *const u8 = s.as_ptr().add(3);
1351 /// println!("{}", *end.sub(1) as char);
1352 /// println!("{}", *end.sub(2) as char);
1355 #[stable(feature = "pointer_methods", since = "1.26.0")]
1357 pub unsafe fn sub(self, count: usize) -> Self
1360 self.offset((count as isize).wrapping_neg())
1363 /// Calculates the offset from a pointer using wrapping arithmetic.
1364 /// (convenience for `.wrapping_offset(count as isize)`)
1366 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1367 /// offset of `3 * size_of::<T>()` bytes.
1371 /// The resulting pointer does not need to be in bounds, but it is
1372 /// potentially hazardous to dereference (which requires `unsafe`).
1374 /// Always use `.add(count)` instead when possible, because `add`
1375 /// allows the compiler to optimize better.
1382 /// // Iterate using a raw pointer in increments of two elements
1383 /// let data = [1u8, 2, 3, 4, 5];
1384 /// let mut ptr: *const u8 = data.as_ptr();
1386 /// let end_rounded_up = ptr.wrapping_add(6);
1388 /// // This loop prints "1, 3, 5, "
1389 /// while ptr != end_rounded_up {
1391 /// print!("{}, ", *ptr);
1393 /// ptr = ptr.wrapping_add(step);
1396 #[stable(feature = "pointer_methods", since = "1.26.0")]
1398 pub fn wrapping_add(self, count: usize) -> Self
1401 self.wrapping_offset(count as isize)
1404 /// Calculates the offset from a pointer using wrapping arithmetic.
1405 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1407 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1408 /// offset of `3 * size_of::<T>()` bytes.
1412 /// The resulting pointer does not need to be in bounds, but it is
1413 /// potentially hazardous to dereference (which requires `unsafe`).
1415 /// Always use `.sub(count)` instead when possible, because `sub`
1416 /// allows the compiler to optimize better.
1423 /// // Iterate using a raw pointer in increments of two elements (backwards)
1424 /// let data = [1u8, 2, 3, 4, 5];
1425 /// let mut ptr: *const u8 = data.as_ptr();
1426 /// let start_rounded_down = ptr.wrapping_sub(2);
1427 /// ptr = ptr.wrapping_add(4);
1429 /// // This loop prints "5, 3, 1, "
1430 /// while ptr != start_rounded_down {
1432 /// print!("{}, ", *ptr);
1434 /// ptr = ptr.wrapping_sub(step);
1437 #[stable(feature = "pointer_methods", since = "1.26.0")]
1439 pub fn wrapping_sub(self, count: usize) -> Self
1442 self.wrapping_offset((count as isize).wrapping_neg())
1445 /// Reads the value from `self` without moving it. This leaves the
1446 /// memory in `self` unchanged.
1448 /// See [`ptr::read`] for safety concerns and examples.
1450 /// [`ptr::read`]: ./ptr/fn.read.html
1451 #[stable(feature = "pointer_methods", since = "1.26.0")]
1453 pub unsafe fn read(self) -> T
1459 /// Performs a volatile read of the value from `self` without moving it. This
1460 /// leaves the memory in `self` unchanged.
1462 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1463 /// to not be elided or reordered by the compiler across other volatile
1466 /// See [`ptr::read_volatile`] for safety concerns and examples.
1468 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
1469 #[stable(feature = "pointer_methods", since = "1.26.0")]
1471 pub unsafe fn read_volatile(self) -> T
1477 /// Reads the value from `self` without moving it. This leaves the
1478 /// memory in `self` unchanged.
1480 /// Unlike `read`, the pointer may be unaligned.
1482 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1484 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
1485 #[stable(feature = "pointer_methods", since = "1.26.0")]
1487 pub unsafe fn read_unaligned(self) -> T
1490 read_unaligned(self)
1493 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1494 /// and destination may overlap.
1496 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1498 /// See [`ptr::copy`] for safety concerns and examples.
1500 /// [`ptr::copy`]: ./ptr/fn.copy.html
1501 #[stable(feature = "pointer_methods", since = "1.26.0")]
1503 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1506 copy(self, dest, count)
1509 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1510 /// and destination may *not* overlap.
1512 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1514 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1516 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
1517 #[stable(feature = "pointer_methods", since = "1.26.0")]
1519 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1522 copy_nonoverlapping(self, dest, count)
1525 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1528 /// If it is not possible to align the pointer, the implementation returns
1529 /// `usize::max_value()`.
1531 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1532 /// used with the `offset` or `offset_to` methods.
1534 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
1535 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1536 /// the returned offset is correct in all terms other than alignment.
1540 /// The function panics if `align` is not a power-of-two.
1544 /// Accessing adjacent `u8` as `u16`
1547 /// # fn foo(n: usize) {
1548 /// # use std::mem::align_of;
1550 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1551 /// let ptr = &x[n] as *const u8;
1552 /// let offset = ptr.align_offset(align_of::<u16>());
1553 /// if offset < x.len() - n - 1 {
1554 /// let u16_ptr = ptr.add(offset) as *const u16;
1555 /// assert_ne!(*u16_ptr, 500);
1557 /// // while the pointer can be aligned via `offset`, it would point
1558 /// // outside the allocation
1562 #[stable(feature = "align_offset", since = "1.36.0")]
1563 pub fn align_offset(self, align: usize) -> usize where T: Sized {
1564 if !align.is_power_of_two() {
1565 panic!("align_offset: align is not a power-of-two");
1568 align_offset(self, align)
1575 impl<T: ?Sized> *mut T {
1576 /// Returns `true` if the pointer is null.
1578 /// Note that unsized types have many possible null pointers, as only the
1579 /// raw data pointer is considered, not their length, vtable, etc.
1580 /// Therefore, two pointers that are null may still not compare equal to
1588 /// let mut s = [1, 2, 3];
1589 /// let ptr: *mut u32 = s.as_mut_ptr();
1590 /// assert!(!ptr.is_null());
1592 #[stable(feature = "rust1", since = "1.0.0")]
1594 pub fn is_null(self) -> bool {
1595 // Compare via a cast to a thin pointer, so fat pointers are only
1596 // considering their "data" part for null-ness.
1597 (self as *mut u8) == null_mut()
1600 /// Cast to a pointer to a different type
1601 #[unstable(feature = "ptr_cast", issue = "60602")]
1603 pub const fn cast<U>(self) -> *mut U {
1607 /// Returns `None` if the pointer is null, or else returns a reference to
1608 /// the value wrapped in `Some`.
1612 /// While this method and its mutable counterpart are useful for
1613 /// null-safety, it is important to note that this is still an unsafe
1614 /// operation because the returned value could be pointing to invalid
1617 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1618 /// not necessarily reflect the actual lifetime of the data.
1625 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1628 /// if let Some(val_back) = ptr.as_ref() {
1629 /// println!("We got back the value: {}!", val_back);
1634 /// # Null-unchecked version
1636 /// If you are sure the pointer can never be null and are looking for some kind of
1637 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1638 /// dereference the pointer directly.
1641 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1644 /// let val_back = &*ptr;
1645 /// println!("We got back the value: {}!", val_back);
1648 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1650 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1658 /// Calculates the offset from a pointer.
1660 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1661 /// offset of `3 * size_of::<T>()` bytes.
1665 /// If any of the following conditions are violated, the result is Undefined
1668 /// * Both the starting and resulting pointer must be either in bounds or one
1669 /// byte past the end of the same allocated object.
1671 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1673 /// * The offset being in bounds cannot rely on "wrapping around" the address
1674 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1676 /// The compiler and standard library generally tries to ensure allocations
1677 /// never reach a size where an offset is a concern. For instance, `Vec`
1678 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1679 /// `vec.as_ptr().add(vec.len())` is always safe.
1681 /// Most platforms fundamentally can't even construct such an allocation.
1682 /// For instance, no known 64-bit platform can ever serve a request
1683 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1684 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1685 /// more than `isize::MAX` bytes with things like Physical Address
1686 /// Extension. As such, memory acquired directly from allocators or memory
1687 /// mapped files *may* be too large to handle with this function.
1689 /// Consider using `wrapping_offset` instead if these constraints are
1690 /// difficult to satisfy. The only advantage of this method is that it
1691 /// enables more aggressive compiler optimizations.
1698 /// let mut s = [1, 2, 3];
1699 /// let ptr: *mut u32 = s.as_mut_ptr();
1702 /// println!("{}", *ptr.offset(1));
1703 /// println!("{}", *ptr.offset(2));
1706 #[stable(feature = "rust1", since = "1.0.0")]
1708 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1709 intrinsics::offset(self, count) as *mut T
1712 /// Calculates the offset from a pointer using wrapping arithmetic.
1713 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1714 /// offset of `3 * size_of::<T>()` bytes.
1718 /// The resulting pointer does not need to be in bounds, but it is
1719 /// potentially hazardous to dereference (which requires `unsafe`).
1720 /// In particular, the resulting pointer may *not* be used to access a
1721 /// different allocated object than the one `self` points to. In other
1722 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1723 /// *not* the same as `y`, and dereferencing it is undefined behavior
1724 /// unless `x` and `y` point into the same allocated object.
1726 /// Always use `.offset(count)` instead when possible, because `offset`
1727 /// allows the compiler to optimize better. If you need to cross object
1728 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1735 /// // Iterate using a raw pointer in increments of two elements
1736 /// let mut data = [1u8, 2, 3, 4, 5];
1737 /// let mut ptr: *mut u8 = data.as_mut_ptr();
1739 /// let end_rounded_up = ptr.wrapping_offset(6);
1741 /// while ptr != end_rounded_up {
1745 /// ptr = ptr.wrapping_offset(step);
1747 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1749 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1751 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1753 intrinsics::arith_offset(self, count) as *mut T
1757 /// Returns `None` if the pointer is null, or else returns a mutable
1758 /// reference to the value wrapped in `Some`.
1762 /// As with `as_ref`, this is unsafe because it cannot verify the validity
1763 /// of the returned pointer, nor can it ensure that the lifetime `'a`
1764 /// returned is indeed a valid lifetime for the contained data.
1771 /// let mut s = [1, 2, 3];
1772 /// let ptr: *mut u32 = s.as_mut_ptr();
1773 /// let first_value = unsafe { ptr.as_mut().unwrap() };
1774 /// *first_value = 4;
1775 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1777 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1779 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1787 /// Calculates the distance between two pointers. The returned value is in
1788 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1790 /// This function is the inverse of [`offset`].
1792 /// [`offset`]: #method.offset-1
1793 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
1797 /// If any of the following conditions are violated, the result is Undefined
1800 /// * Both the starting and other pointer must be either in bounds or one
1801 /// byte past the end of the same allocated object.
1803 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1805 /// * The distance between the pointers, in bytes, must be an exact multiple
1806 /// of the size of `T`.
1808 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1810 /// The compiler and standard library generally try to ensure allocations
1811 /// never reach a size where an offset is a concern. For instance, `Vec`
1812 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1813 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1815 /// Most platforms fundamentally can't even construct such an allocation.
1816 /// For instance, no known 64-bit platform can ever serve a request
1817 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1818 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1819 /// more than `isize::MAX` bytes with things like Physical Address
1820 /// Extension. As such, memory acquired directly from allocators or memory
1821 /// mapped files *may* be too large to handle with this function.
1823 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1824 /// difficult to satisfy. The only advantage of this method is that it
1825 /// enables more aggressive compiler optimizations.
1829 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1836 /// #![feature(ptr_offset_from)]
1838 /// let mut a = [0; 5];
1839 /// let ptr1: *mut i32 = &mut a[1];
1840 /// let ptr2: *mut i32 = &mut a[3];
1842 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1843 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1844 /// assert_eq!(ptr1.offset(2), ptr2);
1845 /// assert_eq!(ptr2.offset(-2), ptr1);
1848 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1850 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1851 (self as *const T).offset_from(origin)
1854 /// Calculates the distance between two pointers. The returned value is in
1855 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1857 /// If the address different between the two pointers is not a multiple of
1858 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1861 /// Though this method is safe for any two pointers, note that its result
1862 /// will be mostly useless if the two pointers aren't into the same allocated
1863 /// object, for example if they point to two different local variables.
1867 /// This function panics if `T` is a zero-sized type.
1874 /// #![feature(ptr_wrapping_offset_from)]
1876 /// let mut a = [0; 5];
1877 /// let ptr1: *mut i32 = &mut a[1];
1878 /// let ptr2: *mut i32 = &mut a[3];
1879 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1880 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1881 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1882 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1884 /// let ptr1: *mut i32 = 3 as _;
1885 /// let ptr2: *mut i32 = 13 as _;
1886 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1888 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1890 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1891 (self as *const T).wrapping_offset_from(origin)
1894 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1896 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1897 /// offset of `3 * size_of::<T>()` bytes.
1901 /// If any of the following conditions are violated, the result is Undefined
1904 /// * Both the starting and resulting pointer must be either in bounds or one
1905 /// byte past the end of the same allocated object.
1907 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1909 /// * The offset being in bounds cannot rely on "wrapping around" the address
1910 /// space. That is, the infinite-precision sum must fit in a `usize`.
1912 /// The compiler and standard library generally tries to ensure allocations
1913 /// never reach a size where an offset is a concern. For instance, `Vec`
1914 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1915 /// `vec.as_ptr().add(vec.len())` is always safe.
1917 /// Most platforms fundamentally can't even construct such an allocation.
1918 /// For instance, no known 64-bit platform can ever serve a request
1919 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1920 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1921 /// more than `isize::MAX` bytes with things like Physical Address
1922 /// Extension. As such, memory acquired directly from allocators or memory
1923 /// mapped files *may* be too large to handle with this function.
1925 /// Consider using `wrapping_offset` instead if these constraints are
1926 /// difficult to satisfy. The only advantage of this method is that it
1927 /// enables more aggressive compiler optimizations.
1934 /// let s: &str = "123";
1935 /// let ptr: *const u8 = s.as_ptr();
1938 /// println!("{}", *ptr.add(1) as char);
1939 /// println!("{}", *ptr.add(2) as char);
1942 #[stable(feature = "pointer_methods", since = "1.26.0")]
1944 pub unsafe fn add(self, count: usize) -> Self
1947 self.offset(count as isize)
1950 /// Calculates the offset from a pointer (convenience for
1951 /// `.offset((count as isize).wrapping_neg())`).
1953 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1954 /// offset of `3 * size_of::<T>()` bytes.
1958 /// If any of the following conditions are violated, the result is Undefined
1961 /// * Both the starting and resulting pointer must be either in bounds or one
1962 /// byte past the end of the same allocated object.
1964 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1966 /// * The offset being in bounds cannot rely on "wrapping around" the address
1967 /// space. That is, the infinite-precision sum must fit in a usize.
1969 /// The compiler and standard library generally tries to ensure allocations
1970 /// never reach a size where an offset is a concern. For instance, `Vec`
1971 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1972 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1974 /// Most platforms fundamentally can't even construct such an allocation.
1975 /// For instance, no known 64-bit platform can ever serve a request
1976 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1977 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1978 /// more than `isize::MAX` bytes with things like Physical Address
1979 /// Extension. As such, memory acquired directly from allocators or memory
1980 /// mapped files *may* be too large to handle with this function.
1982 /// Consider using `wrapping_offset` instead if these constraints are
1983 /// difficult to satisfy. The only advantage of this method is that it
1984 /// enables more aggressive compiler optimizations.
1991 /// let s: &str = "123";
1994 /// let end: *const u8 = s.as_ptr().add(3);
1995 /// println!("{}", *end.sub(1) as char);
1996 /// println!("{}", *end.sub(2) as char);
1999 #[stable(feature = "pointer_methods", since = "1.26.0")]
2001 pub unsafe fn sub(self, count: usize) -> Self
2004 self.offset((count as isize).wrapping_neg())
2007 /// Calculates the offset from a pointer using wrapping arithmetic.
2008 /// (convenience for `.wrapping_offset(count as isize)`)
2010 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2011 /// offset of `3 * size_of::<T>()` bytes.
2015 /// The resulting pointer does not need to be in bounds, but it is
2016 /// potentially hazardous to dereference (which requires `unsafe`).
2018 /// Always use `.add(count)` instead when possible, because `add`
2019 /// allows the compiler to optimize better.
2026 /// // Iterate using a raw pointer in increments of two elements
2027 /// let data = [1u8, 2, 3, 4, 5];
2028 /// let mut ptr: *const u8 = data.as_ptr();
2030 /// let end_rounded_up = ptr.wrapping_add(6);
2032 /// // This loop prints "1, 3, 5, "
2033 /// while ptr != end_rounded_up {
2035 /// print!("{}, ", *ptr);
2037 /// ptr = ptr.wrapping_add(step);
2040 #[stable(feature = "pointer_methods", since = "1.26.0")]
2042 pub fn wrapping_add(self, count: usize) -> Self
2045 self.wrapping_offset(count as isize)
2048 /// Calculates the offset from a pointer using wrapping arithmetic.
2049 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
2051 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2052 /// offset of `3 * size_of::<T>()` bytes.
2056 /// The resulting pointer does not need to be in bounds, but it is
2057 /// potentially hazardous to dereference (which requires `unsafe`).
2059 /// Always use `.sub(count)` instead when possible, because `sub`
2060 /// allows the compiler to optimize better.
2067 /// // Iterate using a raw pointer in increments of two elements (backwards)
2068 /// let data = [1u8, 2, 3, 4, 5];
2069 /// let mut ptr: *const u8 = data.as_ptr();
2070 /// let start_rounded_down = ptr.wrapping_sub(2);
2071 /// ptr = ptr.wrapping_add(4);
2073 /// // This loop prints "5, 3, 1, "
2074 /// while ptr != start_rounded_down {
2076 /// print!("{}, ", *ptr);
2078 /// ptr = ptr.wrapping_sub(step);
2081 #[stable(feature = "pointer_methods", since = "1.26.0")]
2083 pub fn wrapping_sub(self, count: usize) -> Self
2086 self.wrapping_offset((count as isize).wrapping_neg())
2089 /// Reads the value from `self` without moving it. This leaves the
2090 /// memory in `self` unchanged.
2092 /// See [`ptr::read`] for safety concerns and examples.
2094 /// [`ptr::read`]: ./ptr/fn.read.html
2095 #[stable(feature = "pointer_methods", since = "1.26.0")]
2097 pub unsafe fn read(self) -> T
2103 /// Performs a volatile read of the value from `self` without moving it. This
2104 /// leaves the memory in `self` unchanged.
2106 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2107 /// to not be elided or reordered by the compiler across other volatile
2110 /// See [`ptr::read_volatile`] for safety concerns and examples.
2112 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
2113 #[stable(feature = "pointer_methods", since = "1.26.0")]
2115 pub unsafe fn read_volatile(self) -> T
2121 /// Reads the value from `self` without moving it. This leaves the
2122 /// memory in `self` unchanged.
2124 /// Unlike `read`, the pointer may be unaligned.
2126 /// See [`ptr::read_unaligned`] for safety concerns and examples.
2128 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
2129 #[stable(feature = "pointer_methods", since = "1.26.0")]
2131 pub unsafe fn read_unaligned(self) -> T
2134 read_unaligned(self)
2137 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2138 /// and destination may overlap.
2140 /// NOTE: this has the *same* argument order as [`ptr::copy`].
2142 /// See [`ptr::copy`] for safety concerns and examples.
2144 /// [`ptr::copy`]: ./ptr/fn.copy.html
2145 #[stable(feature = "pointer_methods", since = "1.26.0")]
2147 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
2150 copy(self, dest, count)
2153 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2154 /// and destination may *not* overlap.
2156 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
2158 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2160 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2161 #[stable(feature = "pointer_methods", since = "1.26.0")]
2163 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
2166 copy_nonoverlapping(self, dest, count)
2169 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2170 /// and destination may overlap.
2172 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
2174 /// See [`ptr::copy`] for safety concerns and examples.
2176 /// [`ptr::copy`]: ./ptr/fn.copy.html
2177 #[stable(feature = "pointer_methods", since = "1.26.0")]
2179 pub unsafe fn copy_from(self, src: *const T, count: usize)
2182 copy(src, self, count)
2185 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2186 /// and destination may *not* overlap.
2188 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
2190 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2192 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2193 #[stable(feature = "pointer_methods", since = "1.26.0")]
2195 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
2198 copy_nonoverlapping(src, self, count)
2201 /// Executes the destructor (if any) of the pointed-to value.
2203 /// See [`ptr::drop_in_place`] for safety concerns and examples.
2205 /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
2206 #[stable(feature = "pointer_methods", since = "1.26.0")]
2208 pub unsafe fn drop_in_place(self) {
2212 /// Overwrites a memory location with the given value without reading or
2213 /// dropping the old value.
2215 /// See [`ptr::write`] for safety concerns and examples.
2217 /// [`ptr::write`]: ./ptr/fn.write.html
2218 #[stable(feature = "pointer_methods", since = "1.26.0")]
2220 pub unsafe fn write(self, val: T)
2226 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
2227 /// bytes of memory starting at `self` to `val`.
2229 /// See [`ptr::write_bytes`] for safety concerns and examples.
2231 /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
2232 #[stable(feature = "pointer_methods", since = "1.26.0")]
2234 pub unsafe fn write_bytes(self, val: u8, count: usize)
2237 write_bytes(self, val, count)
2240 /// Performs a volatile write of a memory location with the given value without
2241 /// reading or dropping the old value.
2243 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2244 /// to not be elided or reordered by the compiler across other volatile
2247 /// See [`ptr::write_volatile`] for safety concerns and examples.
2249 /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
2250 #[stable(feature = "pointer_methods", since = "1.26.0")]
2252 pub unsafe fn write_volatile(self, val: T)
2255 write_volatile(self, val)
2258 /// Overwrites a memory location with the given value without reading or
2259 /// dropping the old value.
2261 /// Unlike `write`, the pointer may be unaligned.
2263 /// See [`ptr::write_unaligned`] for safety concerns and examples.
2265 /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
2266 #[stable(feature = "pointer_methods", since = "1.26.0")]
2268 pub unsafe fn write_unaligned(self, val: T)
2271 write_unaligned(self, val)
2274 /// Replaces the value at `self` with `src`, returning the old
2275 /// value, without dropping either.
2277 /// See [`ptr::replace`] for safety concerns and examples.
2279 /// [`ptr::replace`]: ./ptr/fn.replace.html
2280 #[stable(feature = "pointer_methods", since = "1.26.0")]
2282 pub unsafe fn replace(self, src: T) -> T
2288 /// Swaps the values at two mutable locations of the same type, without
2289 /// deinitializing either. They may overlap, unlike `mem::swap` which is
2290 /// otherwise equivalent.
2292 /// See [`ptr::swap`] for safety concerns and examples.
2294 /// [`ptr::swap`]: ./ptr/fn.swap.html
2295 #[stable(feature = "pointer_methods", since = "1.26.0")]
2297 pub unsafe fn swap(self, with: *mut T)
2303 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
2306 /// If it is not possible to align the pointer, the implementation returns
2307 /// `usize::max_value()`.
2309 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
2310 /// used with the `offset` or `offset_to` methods.
2312 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
2313 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
2314 /// the returned offset is correct in all terms other than alignment.
2318 /// The function panics if `align` is not a power-of-two.
2322 /// Accessing adjacent `u8` as `u16`
2325 /// # fn foo(n: usize) {
2326 /// # use std::mem::align_of;
2328 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
2329 /// let ptr = &x[n] as *const u8;
2330 /// let offset = ptr.align_offset(align_of::<u16>());
2331 /// if offset < x.len() - n - 1 {
2332 /// let u16_ptr = ptr.add(offset) as *const u16;
2333 /// assert_ne!(*u16_ptr, 500);
2335 /// // while the pointer can be aligned via `offset`, it would point
2336 /// // outside the allocation
2340 #[stable(feature = "align_offset", since = "1.36.0")]
2341 pub fn align_offset(self, align: usize) -> usize where T: Sized {
2342 if !align.is_power_of_two() {
2343 panic!("align_offset: align is not a power-of-two");
2346 align_offset(self, align)
2351 /// Align pointer `p`.
2353 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
2354 /// to pointer `p` so that pointer `p` would get aligned to `a`.
2356 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
2357 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2360 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2361 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2362 /// than trying to adapt this to accommodate that change.
2364 /// Any questions go to @nagisa.
2365 #[lang="align_offset"]
2366 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2367 /// Calculate multiplicative modular inverse of `x` modulo `m`.
2369 /// This implementation is tailored for align_offset and has following preconditions:
2371 /// * `m` is a power-of-two;
2372 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2374 /// Implementation of this function shall not panic. Ever.
2376 fn mod_inv(x: usize, m: usize) -> usize {
2377 /// Multiplicative modular inverse table modulo 2⁴ = 16.
2379 /// Note, that this table does not contain values where inverse does not exist (i.e., for
2380 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2381 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2382 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2383 const INV_TABLE_MOD: usize = 16;
2385 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
2387 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
2388 if m <= INV_TABLE_MOD {
2389 table_inverse & (m - 1)
2391 // We iterate "up" using the following formula:
2393 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2395 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
2396 let mut inverse = table_inverse;
2397 let mut going_mod = INV_TABLE_MOD_SQUARED;
2399 // y = y * (2 - xy) mod n
2401 // Note, that we use wrapping operations here intentionally – the original formula
2402 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
2403 // usize::max_value()` instead, because we take the result `mod n` at the end
2405 inverse = inverse.wrapping_mul(
2406 2usize.wrapping_sub(x.wrapping_mul(inverse))
2407 ) & (going_mod - 1);
2409 return inverse & (m - 1);
2411 going_mod = going_mod.wrapping_mul(going_mod);
2416 let stride = mem::size_of::<T>();
2417 let a_minus_one = a.wrapping_sub(1);
2418 let pmoda = p as usize & a_minus_one;
2421 // Already aligned. Yay!
2426 return if stride == 0 {
2427 // If the pointer is not aligned, and the element is zero-sized, then no amount of
2428 // elements will ever align the pointer.
2431 a.wrapping_sub(pmoda)
2435 let smoda = stride & a_minus_one;
2436 // a is power-of-two so cannot be 0. stride = 0 is handled above.
2437 let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
2438 let gcd = 1usize << gcdpow;
2440 if p as usize & (gcd - 1) == 0 {
2441 // This branch solves for the following linear congruence equation:
2443 // $$ p + so ≡ 0 mod a $$
2445 // $p$ here is the pointer value, $s$ – stride of `T`, $o$ offset in `T`s, and $a$ – the
2446 // requested alignment.
2449 // o = (a - (p mod a))/g * ((s/g)⁻¹ mod a)
2451 // The first term is “the relative alignment of p to a”, the second term is “how does
2452 // incrementing p by s bytes change the relative alignment of p”. Division by `g` is
2453 // necessary to make this equation well formed if $a$ and $s$ are not co-prime.
2455 // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
2456 // to take the result $o mod lcm(s, a)$. We can replace $lcm(s, a)$ with just a $a / g$.
2457 let j = a.wrapping_sub(pmoda) >> gcdpow;
2458 let k = smoda >> gcdpow;
2459 return intrinsics::unchecked_rem(j.wrapping_mul(mod_inv(k, a)), a >> gcdpow);
2462 // Cannot be aligned at all.
2468 // Equality for pointers
2469 #[stable(feature = "rust1", since = "1.0.0")]
2470 impl<T: ?Sized> PartialEq for *const T {
2472 fn eq(&self, other: &*const T) -> bool { *self == *other }
2475 #[stable(feature = "rust1", since = "1.0.0")]
2476 impl<T: ?Sized> Eq for *const T {}
2478 #[stable(feature = "rust1", since = "1.0.0")]
2479 impl<T: ?Sized> PartialEq for *mut T {
2481 fn eq(&self, other: &*mut T) -> bool { *self == *other }
2484 #[stable(feature = "rust1", since = "1.0.0")]
2485 impl<T: ?Sized> Eq for *mut T {}
2487 /// Compares raw pointers for equality.
2489 /// This is the same as using the `==` operator, but less generic:
2490 /// the arguments have to be `*const T` raw pointers,
2491 /// not anything that implements `PartialEq`.
2493 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2494 /// by their address rather than comparing the values they point to
2495 /// (which is what the `PartialEq for &T` implementation does).
2503 /// let other_five = 5;
2504 /// let five_ref = &five;
2505 /// let same_five_ref = &five;
2506 /// let other_five_ref = &other_five;
2508 /// assert!(five_ref == same_five_ref);
2509 /// assert!(ptr::eq(five_ref, same_five_ref));
2511 /// assert!(five_ref == other_five_ref);
2512 /// assert!(!ptr::eq(five_ref, other_five_ref));
2515 /// Slices are also compared by their length (fat pointers):
2518 /// let a = [1, 2, 3];
2519 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
2520 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
2521 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
2524 /// Traits are also compared by their implementation:
2527 /// #[repr(transparent)]
2528 /// struct Wrapper { member: i32 }
2531 /// impl Trait for Wrapper {}
2532 /// impl Trait for i32 {}
2535 /// let wrapper = Wrapper { member: 10 };
2537 /// // Pointers have equal addresses.
2538 /// assert!(std::ptr::eq(
2539 /// &wrapper as *const Wrapper as *const u8,
2540 /// &wrapper.member as *const i32 as *const u8
2543 /// // Objects have equal addresses, but `Trait` has different implementations.
2544 /// assert!(!std::ptr::eq(
2545 /// &wrapper as &dyn Trait,
2546 /// &wrapper.member as &dyn Trait,
2548 /// assert!(!std::ptr::eq(
2549 /// &wrapper as &dyn Trait as *const dyn Trait,
2550 /// &wrapper.member as &dyn Trait as *const dyn Trait,
2553 /// // Converting the reference to a `*const u8` compares by address.
2554 /// assert!(std::ptr::eq(
2555 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
2556 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
2560 #[stable(feature = "ptr_eq", since = "1.17.0")]
2562 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2566 /// Hash a raw pointer.
2568 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
2569 /// by its address rather than the value it points to
2570 /// (which is what the `Hash for &T` implementation does).
2575 /// use std::collections::hash_map::DefaultHasher;
2576 /// use std::hash::{Hash, Hasher};
2580 /// let five_ref = &five;
2582 /// let mut hasher = DefaultHasher::new();
2583 /// ptr::hash(five_ref, &mut hasher);
2584 /// let actual = hasher.finish();
2586 /// let mut hasher = DefaultHasher::new();
2587 /// (five_ref as *const i32).hash(&mut hasher);
2588 /// let expected = hasher.finish();
2590 /// assert_eq!(actual, expected);
2592 #[stable(feature = "ptr_hash", since = "1.35.0")]
2593 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
2594 use crate::hash::Hash;
2598 // Impls for function pointers
2599 macro_rules! fnptr_impls_safety_abi {
2600 ($FnTy: ty, $($Arg: ident),*) => {
2601 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2602 impl<Ret, $($Arg),*> PartialEq for $FnTy {
2604 fn eq(&self, other: &Self) -> bool {
2605 *self as usize == *other as usize
2609 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2610 impl<Ret, $($Arg),*> Eq for $FnTy {}
2612 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2613 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2615 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2616 (*self as usize).partial_cmp(&(*other as usize))
2620 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2621 impl<Ret, $($Arg),*> Ord for $FnTy {
2623 fn cmp(&self, other: &Self) -> Ordering {
2624 (*self as usize).cmp(&(*other as usize))
2628 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2629 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2630 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2631 state.write_usize(*self as usize)
2635 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2636 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2637 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2638 fmt::Pointer::fmt(&(*self as *const ()), f)
2642 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2643 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2644 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2645 fmt::Pointer::fmt(&(*self as *const ()), f)
2651 macro_rules! fnptr_impls_args {
2652 ($($Arg: ident),+) => {
2653 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2654 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2655 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2656 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2657 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2658 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2661 // No variadic functions with 0 parameters
2662 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2663 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2664 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2665 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2669 fnptr_impls_args! { }
2670 fnptr_impls_args! { A }
2671 fnptr_impls_args! { A, B }
2672 fnptr_impls_args! { A, B, C }
2673 fnptr_impls_args! { A, B, C, D }
2674 fnptr_impls_args! { A, B, C, D, E }
2675 fnptr_impls_args! { A, B, C, D, E, F }
2676 fnptr_impls_args! { A, B, C, D, E, F, G }
2677 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2678 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2679 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2680 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2681 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2683 // Comparison for pointers
2684 #[stable(feature = "rust1", since = "1.0.0")]
2685 impl<T: ?Sized> Ord for *const T {
2687 fn cmp(&self, other: &*const T) -> Ordering {
2690 } else if self == other {
2698 #[stable(feature = "rust1", since = "1.0.0")]
2699 impl<T: ?Sized> PartialOrd for *const T {
2701 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2702 Some(self.cmp(other))
2706 fn lt(&self, other: &*const T) -> bool { *self < *other }
2709 fn le(&self, other: &*const T) -> bool { *self <= *other }
2712 fn gt(&self, other: &*const T) -> bool { *self > *other }
2715 fn ge(&self, other: &*const T) -> bool { *self >= *other }
2718 #[stable(feature = "rust1", since = "1.0.0")]
2719 impl<T: ?Sized> Ord for *mut T {
2721 fn cmp(&self, other: &*mut T) -> Ordering {
2724 } else if self == other {
2732 #[stable(feature = "rust1", since = "1.0.0")]
2733 impl<T: ?Sized> PartialOrd for *mut T {
2735 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2736 Some(self.cmp(other))
2740 fn lt(&self, other: &*mut T) -> bool { *self < *other }
2743 fn le(&self, other: &*mut T) -> bool { *self <= *other }
2746 fn gt(&self, other: &*mut T) -> bool { *self > *other }
2749 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
2752 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
2753 /// of this wrapper owns the referent. Useful for building abstractions like
2754 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
2756 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
2757 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
2758 /// the kind of strong aliasing guarantees an instance of `T` can expect:
2759 /// the referent of the pointer should not be modified without a unique path to
2760 /// its owning Unique.
2762 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
2763 /// consider using `NonNull`, which has weaker semantics.
2765 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2766 /// is never dereferenced. This is so that enums may use this forbidden value
2767 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
2768 /// However the pointer may still dangle if it isn't dereferenced.
2770 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
2771 /// for any type which upholds Unique's aliasing requirements.
2772 #[unstable(feature = "ptr_internals", issue = "0",
2773 reason = "use NonNull instead and consider PhantomData<T> \
2774 (if you also use #[may_dangle]), Send, and/or Sync")]
2776 #[repr(transparent)]
2777 #[rustc_layout_scalar_valid_range_start(1)]
2778 pub struct Unique<T: ?Sized> {
2780 // NOTE: this marker has no consequences for variance, but is necessary
2781 // for dropck to understand that we logically own a `T`.
2783 // For details, see:
2784 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
2785 _marker: PhantomData<T>,
2788 #[unstable(feature = "ptr_internals", issue = "0")]
2789 impl<T: ?Sized> fmt::Debug for Unique<T> {
2790 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2791 fmt::Pointer::fmt(&self.as_ptr(), f)
2795 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
2796 /// reference is unaliased. Note that this aliasing invariant is
2797 /// unenforced by the type system; the abstraction using the
2798 /// `Unique` must enforce it.
2799 #[unstable(feature = "ptr_internals", issue = "0")]
2800 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
2802 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
2803 /// reference is unaliased. Note that this aliasing invariant is
2804 /// unenforced by the type system; the abstraction using the
2805 /// `Unique` must enforce it.
2806 #[unstable(feature = "ptr_internals", issue = "0")]
2807 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
2809 #[unstable(feature = "ptr_internals", issue = "0")]
2810 impl<T: Sized> Unique<T> {
2811 /// Creates a new `Unique` that is dangling, but well-aligned.
2813 /// This is useful for initializing types which lazily allocate, like
2814 /// `Vec::new` does.
2816 /// Note that the pointer value may potentially represent a valid pointer to
2817 /// a `T`, which means this must not be used as a "not yet initialized"
2818 /// sentinel value. Types that lazily allocate must track initialization by
2819 /// some other means.
2820 // FIXME: rename to dangling() to match NonNull?
2821 pub const fn empty() -> Self {
2823 Unique::new_unchecked(mem::align_of::<T>() as *mut T)
2828 #[unstable(feature = "ptr_internals", issue = "0")]
2829 impl<T: ?Sized> Unique<T> {
2830 /// Creates a new `Unique`.
2834 /// `ptr` must be non-null.
2835 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2836 Unique { pointer: ptr as _, _marker: PhantomData }
2839 /// Creates a new `Unique` if `ptr` is non-null.
2840 pub fn new(ptr: *mut T) -> Option<Self> {
2842 Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
2848 /// Acquires the underlying `*mut` pointer.
2849 pub const fn as_ptr(self) -> *mut T {
2850 self.pointer as *mut T
2853 /// Dereferences the content.
2855 /// The resulting lifetime is bound to self so this behaves "as if"
2856 /// it were actually an instance of T that is getting borrowed. If a longer
2857 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2858 pub unsafe fn as_ref(&self) -> &T {
2862 /// Mutably dereferences the content.
2864 /// The resulting lifetime is bound to self so this behaves "as if"
2865 /// it were actually an instance of T that is getting borrowed. If a longer
2866 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2867 pub unsafe fn as_mut(&mut self) -> &mut T {
2872 #[unstable(feature = "ptr_internals", issue = "0")]
2873 impl<T: ?Sized> Clone for Unique<T> {
2874 fn clone(&self) -> Self {
2879 #[unstable(feature = "ptr_internals", issue = "0")]
2880 impl<T: ?Sized> Copy for Unique<T> { }
2882 #[unstable(feature = "ptr_internals", issue = "0")]
2883 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
2885 #[unstable(feature = "ptr_internals", issue = "0")]
2886 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> { }
2888 #[unstable(feature = "ptr_internals", issue = "0")]
2889 impl<T: ?Sized> fmt::Pointer for Unique<T> {
2890 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2891 fmt::Pointer::fmt(&self.as_ptr(), f)
2895 #[unstable(feature = "ptr_internals", issue = "0")]
2896 impl<T: ?Sized> From<&mut T> for Unique<T> {
2897 fn from(reference: &mut T) -> Self {
2898 unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
2902 #[unstable(feature = "ptr_internals", issue = "0")]
2903 impl<T: ?Sized> From<&T> for Unique<T> {
2904 fn from(reference: &T) -> Self {
2905 unsafe { Unique { pointer: reference as *const T, _marker: PhantomData } }
2909 #[unstable(feature = "ptr_internals", issue = "0")]
2910 impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
2911 fn from(p: NonNull<T>) -> Self {
2912 unsafe { Unique { pointer: p.pointer, _marker: PhantomData } }
2916 /// `*mut T` but non-zero and covariant.
2918 /// This is often the correct thing to use when building data structures using
2919 /// raw pointers, but is ultimately more dangerous to use because of its additional
2920 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
2922 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2923 /// is never dereferenced. This is so that enums may use this forbidden value
2924 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
2925 /// However the pointer may still dangle if it isn't dereferenced.
2927 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
2928 /// for your use case, you should include some [`PhantomData`] in your type to
2929 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
2930 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
2931 /// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they
2932 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
2934 /// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
2935 /// not change the fact that mutating through a (pointer derived from a) shared
2936 /// reference is undefined behavior unless the mutation happens inside an
2937 /// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
2938 /// reference. When using this `From` instance without an `UnsafeCell<T>`,
2939 /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
2940 /// is never used for mutation.
2942 /// [`PhantomData`]: ../marker/struct.PhantomData.html
2943 /// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
2944 #[stable(feature = "nonnull", since = "1.25.0")]
2945 #[repr(transparent)]
2946 #[rustc_layout_scalar_valid_range_start(1)]
2947 pub struct NonNull<T: ?Sized> {
2951 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
2952 // N.B., this impl is unnecessary, but should provide better error messages.
2953 #[stable(feature = "nonnull", since = "1.25.0")]
2954 impl<T: ?Sized> !Send for NonNull<T> { }
2956 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
2957 // N.B., this impl is unnecessary, but should provide better error messages.
2958 #[stable(feature = "nonnull", since = "1.25.0")]
2959 impl<T: ?Sized> !Sync for NonNull<T> { }
2961 impl<T: Sized> NonNull<T> {
2962 /// Creates a new `NonNull` that is dangling, but well-aligned.
2964 /// This is useful for initializing types which lazily allocate, like
2965 /// `Vec::new` does.
2967 /// Note that the pointer value may potentially represent a valid pointer to
2968 /// a `T`, which means this must not be used as a "not yet initialized"
2969 /// sentinel value. Types that lazily allocate must track initialization by
2970 /// some other means.
2971 #[stable(feature = "nonnull", since = "1.25.0")]
2973 pub const fn dangling() -> Self {
2975 let ptr = mem::align_of::<T>() as *mut T;
2976 NonNull::new_unchecked(ptr)
2981 impl<T: ?Sized> NonNull<T> {
2982 /// Creates a new `NonNull`.
2986 /// `ptr` must be non-null.
2987 #[stable(feature = "nonnull", since = "1.25.0")]
2989 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2990 NonNull { pointer: ptr as _ }
2993 /// Creates a new `NonNull` if `ptr` is non-null.
2994 #[stable(feature = "nonnull", since = "1.25.0")]
2996 pub fn new(ptr: *mut T) -> Option<Self> {
2998 Some(unsafe { Self::new_unchecked(ptr) })
3004 /// Acquires the underlying `*mut` pointer.
3005 #[stable(feature = "nonnull", since = "1.25.0")]
3007 pub const fn as_ptr(self) -> *mut T {
3008 self.pointer as *mut T
3011 /// Dereferences the content.
3013 /// The resulting lifetime is bound to self so this behaves "as if"
3014 /// it were actually an instance of T that is getting borrowed. If a longer
3015 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
3016 #[stable(feature = "nonnull", since = "1.25.0")]
3018 pub unsafe fn as_ref(&self) -> &T {
3022 /// Mutably dereferences the content.
3024 /// The resulting lifetime is bound to self so this behaves "as if"
3025 /// it were actually an instance of T that is getting borrowed. If a longer
3026 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
3027 #[stable(feature = "nonnull", since = "1.25.0")]
3029 pub unsafe fn as_mut(&mut self) -> &mut T {
3033 /// Cast to a pointer of another type
3034 #[stable(feature = "nonnull_cast", since = "1.27.0")]
3036 pub const fn cast<U>(self) -> NonNull<U> {
3038 NonNull::new_unchecked(self.as_ptr() as *mut U)
3043 #[stable(feature = "nonnull", since = "1.25.0")]
3044 impl<T: ?Sized> Clone for NonNull<T> {
3045 fn clone(&self) -> Self {
3050 #[stable(feature = "nonnull", since = "1.25.0")]
3051 impl<T: ?Sized> Copy for NonNull<T> { }
3053 #[unstable(feature = "coerce_unsized", issue = "27732")]
3054 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
3056 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
3057 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
3059 #[stable(feature = "nonnull", since = "1.25.0")]
3060 impl<T: ?Sized> fmt::Debug for NonNull<T> {
3061 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3062 fmt::Pointer::fmt(&self.as_ptr(), f)
3066 #[stable(feature = "nonnull", since = "1.25.0")]
3067 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
3068 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3069 fmt::Pointer::fmt(&self.as_ptr(), f)
3073 #[stable(feature = "nonnull", since = "1.25.0")]
3074 impl<T: ?Sized> Eq for NonNull<T> {}
3076 #[stable(feature = "nonnull", since = "1.25.0")]
3077 impl<T: ?Sized> PartialEq for NonNull<T> {
3079 fn eq(&self, other: &Self) -> bool {
3080 self.as_ptr() == other.as_ptr()
3084 #[stable(feature = "nonnull", since = "1.25.0")]
3085 impl<T: ?Sized> Ord for NonNull<T> {
3087 fn cmp(&self, other: &Self) -> Ordering {
3088 self.as_ptr().cmp(&other.as_ptr())
3092 #[stable(feature = "nonnull", since = "1.25.0")]
3093 impl<T: ?Sized> PartialOrd for NonNull<T> {
3095 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3096 self.as_ptr().partial_cmp(&other.as_ptr())
3100 #[stable(feature = "nonnull", since = "1.25.0")]
3101 impl<T: ?Sized> hash::Hash for NonNull<T> {
3103 fn hash<H: hash::Hasher>(&self, state: &mut H) {
3104 self.as_ptr().hash(state)
3108 #[unstable(feature = "ptr_internals", issue = "0")]
3109 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
3111 fn from(unique: Unique<T>) -> Self {
3112 unsafe { NonNull { pointer: unique.pointer } }
3116 #[stable(feature = "nonnull", since = "1.25.0")]
3117 impl<T: ?Sized> From<&mut T> for NonNull<T> {
3119 fn from(reference: &mut T) -> Self {
3120 unsafe { NonNull { pointer: reference as *mut T } }
3124 #[stable(feature = "nonnull", since = "1.25.0")]
3125 impl<T: ?Sized> From<&T> for NonNull<T> {
3127 fn from(reference: &T) -> Self {
3128 unsafe { NonNull { pointer: reference as *const T } }