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 /// [`write_volatile`]: ./fn.write_volatile.html
817 /// Rust does not currently have a rigorously and formally defined memory model,
818 /// so the precise semantics of what "volatile" means here is subject to change
819 /// over time. That being said, the semantics will almost always end up pretty
820 /// similar to [C11's definition of volatile][c11].
822 /// The compiler shouldn't change the relative order or number of volatile
823 /// memory operations. However, volatile memory operations on zero-sized types
824 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
825 /// and may be ignored.
827 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
831 /// Behavior is undefined if any of the following conditions are violated:
833 /// * `src` must be [valid] for reads.
835 /// * `src` must be properly aligned.
837 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
838 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
839 /// value and the value at `*src` can [violate memory safety][read-ownership].
840 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
843 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
845 /// [valid]: ../ptr/index.html#safety
846 /// [`Copy`]: ../marker/trait.Copy.html
847 /// [`read`]: ./fn.read.html
848 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
850 /// Just like in C, whether an operation is volatile has no bearing whatsoever
851 /// on questions involving concurrent access from multiple threads. Volatile
852 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
853 /// a race between a `read_volatile` and any write operation to the same location
854 /// is undefined behavior.
862 /// let y = &x as *const i32;
865 /// assert_eq!(std::ptr::read_volatile(y), 12);
869 #[stable(feature = "volatile", since = "1.9.0")]
870 pub unsafe fn read_volatile<T>(src: *const T) -> T {
871 intrinsics::volatile_load(src)
874 /// Performs a volatile write of a memory location with the given value without
875 /// reading or dropping the old value.
877 /// Volatile operations are intended to act on I/O memory, and are guaranteed
878 /// to not be elided or reordered by the compiler across other volatile
881 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
882 /// could leak allocations or resources, so care should be taken not to overwrite
883 /// an object that should be dropped.
885 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
886 /// location pointed to by `dst`.
888 /// [`read_volatile`]: ./fn.read_volatile.html
892 /// Rust does not currently have a rigorously and formally defined memory model,
893 /// so the precise semantics of what "volatile" means here is subject to change
894 /// over time. That being said, the semantics will almost always end up pretty
895 /// similar to [C11's definition of volatile][c11].
897 /// The compiler shouldn't change the relative order or number of volatile
898 /// memory operations. However, volatile memory operations on zero-sized types
899 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
900 /// and may be ignored.
902 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
906 /// Behavior is undefined if any of the following conditions are violated:
908 /// * `dst` must be [valid] for writes.
910 /// * `dst` must be properly aligned.
912 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
914 /// [valid]: ../ptr/index.html#safety
916 /// Just like in C, whether an operation is volatile has no bearing whatsoever
917 /// on questions involving concurrent access from multiple threads. Volatile
918 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
919 /// a race between a `write_volatile` and any other operation (reading or writing)
920 /// on the same location is undefined behavior.
928 /// let y = &mut x as *mut i32;
932 /// std::ptr::write_volatile(y, z);
933 /// assert_eq!(std::ptr::read_volatile(y), 12);
937 #[stable(feature = "volatile", since = "1.9.0")]
938 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
939 intrinsics::volatile_store(dst, src);
942 #[lang = "const_ptr"]
943 impl<T: ?Sized> *const T {
944 /// Returns `true` if the pointer is null.
946 /// Note that unsized types have many possible null pointers, as only the
947 /// raw data pointer is considered, not their length, vtable, etc.
948 /// Therefore, two pointers that are null may still not compare equal to
956 /// let s: &str = "Follow the rabbit";
957 /// let ptr: *const u8 = s.as_ptr();
958 /// assert!(!ptr.is_null());
960 #[stable(feature = "rust1", since = "1.0.0")]
962 pub fn is_null(self) -> bool {
963 // Compare via a cast to a thin pointer, so fat pointers are only
964 // considering their "data" part for null-ness.
965 (self as *const u8) == null()
968 /// Cast to a pointer to a different type
969 #[unstable(feature = "ptr_cast", issue = "60602")]
971 pub const fn cast<U>(self) -> *const U {
975 /// Returns `None` if the pointer is null, or else returns a reference to
976 /// the value wrapped in `Some`.
980 /// While this method and its mutable counterpart are useful for
981 /// null-safety, it is important to note that this is still an unsafe
982 /// operation because the returned value could be pointing to invalid
985 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
986 /// not necessarily reflect the actual lifetime of the data.
993 /// let ptr: *const u8 = &10u8 as *const u8;
996 /// if let Some(val_back) = ptr.as_ref() {
997 /// println!("We got back the value: {}!", val_back);
1002 /// # Null-unchecked version
1004 /// If you are sure the pointer can never be null and are looking for some kind of
1005 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1006 /// dereference the pointer directly.
1009 /// let ptr: *const u8 = &10u8 as *const u8;
1012 /// let val_back = &*ptr;
1013 /// println!("We got back the value: {}!", val_back);
1016 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1018 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1026 /// Calculates the offset from a pointer.
1028 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1029 /// offset of `3 * size_of::<T>()` bytes.
1033 /// If any of the following conditions are violated, the result is Undefined
1036 /// * Both the starting and resulting pointer must be either in bounds or one
1037 /// byte past the end of the same allocated object.
1039 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1041 /// * The offset being in bounds cannot rely on "wrapping around" the address
1042 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1044 /// The compiler and standard library generally tries to ensure allocations
1045 /// never reach a size where an offset is a concern. For instance, `Vec`
1046 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1047 /// `vec.as_ptr().add(vec.len())` is always safe.
1049 /// Most platforms fundamentally can't even construct such an allocation.
1050 /// For instance, no known 64-bit platform can ever serve a request
1051 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1052 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1053 /// more than `isize::MAX` bytes with things like Physical Address
1054 /// Extension. As such, memory acquired directly from allocators or memory
1055 /// mapped files *may* be too large to handle with this function.
1057 /// Consider using `wrapping_offset` instead if these constraints are
1058 /// difficult to satisfy. The only advantage of this method is that it
1059 /// enables more aggressive compiler optimizations.
1066 /// let s: &str = "123";
1067 /// let ptr: *const u8 = s.as_ptr();
1070 /// println!("{}", *ptr.offset(1) as char);
1071 /// println!("{}", *ptr.offset(2) as char);
1074 #[stable(feature = "rust1", since = "1.0.0")]
1076 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
1077 intrinsics::offset(self, count)
1080 /// Calculates the offset from a pointer using wrapping arithmetic.
1082 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1083 /// offset of `3 * size_of::<T>()` bytes.
1087 /// The resulting pointer does not need to be in bounds, but it is
1088 /// potentially hazardous to dereference (which requires `unsafe`).
1089 /// In particular, the resulting pointer may *not* be used to access a
1090 /// different allocated object than the one `self` points to. In other
1091 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1092 /// *not* the same as `y`, and dereferencing it is undefined behavior
1093 /// unless `x` and `y` point into the same allocated object.
1095 /// Always use `.offset(count)` instead when possible, because `offset`
1096 /// allows the compiler to optimize better. If you need to cross object
1097 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1104 /// // Iterate using a raw pointer in increments of two elements
1105 /// let data = [1u8, 2, 3, 4, 5];
1106 /// let mut ptr: *const u8 = data.as_ptr();
1108 /// let end_rounded_up = ptr.wrapping_offset(6);
1110 /// // This loop prints "1, 3, 5, "
1111 /// while ptr != end_rounded_up {
1113 /// print!("{}, ", *ptr);
1115 /// ptr = ptr.wrapping_offset(step);
1118 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1120 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
1122 intrinsics::arith_offset(self, count)
1126 /// Calculates the distance between two pointers. The returned value is in
1127 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1129 /// This function is the inverse of [`offset`].
1131 /// [`offset`]: #method.offset
1132 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
1136 /// If any of the following conditions are violated, the result is Undefined
1139 /// * Both the starting and other pointer must be either in bounds or one
1140 /// byte past the end of the same allocated object.
1142 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1144 /// * The distance between the pointers, in bytes, must be an exact multiple
1145 /// of the size of `T`.
1147 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1149 /// The compiler and standard library generally try to ensure allocations
1150 /// never reach a size where an offset is a concern. For instance, `Vec`
1151 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1152 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1154 /// Most platforms fundamentally can't even construct such an allocation.
1155 /// For instance, no known 64-bit platform can ever serve a request
1156 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1157 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1158 /// more than `isize::MAX` bytes with things like Physical Address
1159 /// Extension. As such, memory acquired directly from allocators or memory
1160 /// mapped files *may* be too large to handle with this function.
1162 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1163 /// difficult to satisfy. The only advantage of this method is that it
1164 /// enables more aggressive compiler optimizations.
1168 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1175 /// #![feature(ptr_offset_from)]
1178 /// let ptr1: *const i32 = &a[1];
1179 /// let ptr2: *const i32 = &a[3];
1181 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1182 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1183 /// assert_eq!(ptr1.offset(2), ptr2);
1184 /// assert_eq!(ptr2.offset(-2), ptr1);
1187 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1189 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1190 let pointee_size = mem::size_of::<T>();
1191 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1193 // This is the same sequence that Clang emits for pointer subtraction.
1194 // It can be neither `nsw` nor `nuw` because the input is treated as
1195 // unsigned but then the output is treated as signed, so neither works.
1196 let d = isize::wrapping_sub(self as _, origin as _);
1197 intrinsics::exact_div(d, pointee_size as _)
1200 /// Calculates the distance between two pointers. The returned value is in
1201 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1203 /// If the address different between the two pointers is not a multiple of
1204 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1207 /// Though this method is safe for any two pointers, note that its result
1208 /// will be mostly useless if the two pointers aren't into the same allocated
1209 /// object, for example if they point to two different local variables.
1213 /// This function panics if `T` is a zero-sized type.
1220 /// #![feature(ptr_wrapping_offset_from)]
1223 /// let ptr1: *const i32 = &a[1];
1224 /// let ptr2: *const i32 = &a[3];
1225 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1226 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1227 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1228 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1230 /// let ptr1: *const i32 = 3 as _;
1231 /// let ptr2: *const i32 = 13 as _;
1232 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1234 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1236 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1237 let pointee_size = mem::size_of::<T>();
1238 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1240 let d = isize::wrapping_sub(self as _, origin as _);
1241 d.wrapping_div(pointee_size as _)
1244 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1246 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1247 /// offset of `3 * size_of::<T>()` bytes.
1251 /// If any of the following conditions are violated, the result is Undefined
1254 /// * Both the starting and resulting pointer must be either in bounds or one
1255 /// byte past the end of the same allocated object.
1257 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1259 /// * The offset being in bounds cannot rely on "wrapping around" the address
1260 /// space. That is, the infinite-precision sum must fit in a `usize`.
1262 /// The compiler and standard library generally tries to ensure allocations
1263 /// never reach a size where an offset is a concern. For instance, `Vec`
1264 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1265 /// `vec.as_ptr().add(vec.len())` is always safe.
1267 /// Most platforms fundamentally can't even construct such an allocation.
1268 /// For instance, no known 64-bit platform can ever serve a request
1269 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1270 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1271 /// more than `isize::MAX` bytes with things like Physical Address
1272 /// Extension. As such, memory acquired directly from allocators or memory
1273 /// mapped files *may* be too large to handle with this function.
1275 /// Consider using `wrapping_offset` instead if these constraints are
1276 /// difficult to satisfy. The only advantage of this method is that it
1277 /// enables more aggressive compiler optimizations.
1284 /// let s: &str = "123";
1285 /// let ptr: *const u8 = s.as_ptr();
1288 /// println!("{}", *ptr.add(1) as char);
1289 /// println!("{}", *ptr.add(2) as char);
1292 #[stable(feature = "pointer_methods", since = "1.26.0")]
1294 pub unsafe fn add(self, count: usize) -> Self
1297 self.offset(count as isize)
1300 /// Calculates the offset from a pointer (convenience for
1301 /// `.offset((count as isize).wrapping_neg())`).
1303 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1304 /// offset of `3 * size_of::<T>()` bytes.
1308 /// If any of the following conditions are violated, the result is Undefined
1311 /// * Both the starting and resulting pointer must be either in bounds or one
1312 /// byte past the end of the same allocated object.
1314 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1316 /// * The offset being in bounds cannot rely on "wrapping around" the address
1317 /// space. That is, the infinite-precision sum must fit in a usize.
1319 /// The compiler and standard library generally tries to ensure allocations
1320 /// never reach a size where an offset is a concern. For instance, `Vec`
1321 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1322 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1324 /// Most platforms fundamentally can't even construct such an allocation.
1325 /// For instance, no known 64-bit platform can ever serve a request
1326 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1327 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1328 /// more than `isize::MAX` bytes with things like Physical Address
1329 /// Extension. As such, memory acquired directly from allocators or memory
1330 /// mapped files *may* be too large to handle with this function.
1332 /// Consider using `wrapping_offset` instead if these constraints are
1333 /// difficult to satisfy. The only advantage of this method is that it
1334 /// enables more aggressive compiler optimizations.
1341 /// let s: &str = "123";
1344 /// let end: *const u8 = s.as_ptr().add(3);
1345 /// println!("{}", *end.sub(1) as char);
1346 /// println!("{}", *end.sub(2) as char);
1349 #[stable(feature = "pointer_methods", since = "1.26.0")]
1351 pub unsafe fn sub(self, count: usize) -> Self
1354 self.offset((count as isize).wrapping_neg())
1357 /// Calculates the offset from a pointer using wrapping arithmetic.
1358 /// (convenience for `.wrapping_offset(count as isize)`)
1360 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1361 /// offset of `3 * size_of::<T>()` bytes.
1365 /// The resulting pointer does not need to be in bounds, but it is
1366 /// potentially hazardous to dereference (which requires `unsafe`).
1368 /// Always use `.add(count)` instead when possible, because `add`
1369 /// allows the compiler to optimize better.
1376 /// // Iterate using a raw pointer in increments of two elements
1377 /// let data = [1u8, 2, 3, 4, 5];
1378 /// let mut ptr: *const u8 = data.as_ptr();
1380 /// let end_rounded_up = ptr.wrapping_add(6);
1382 /// // This loop prints "1, 3, 5, "
1383 /// while ptr != end_rounded_up {
1385 /// print!("{}, ", *ptr);
1387 /// ptr = ptr.wrapping_add(step);
1390 #[stable(feature = "pointer_methods", since = "1.26.0")]
1392 pub fn wrapping_add(self, count: usize) -> Self
1395 self.wrapping_offset(count as isize)
1398 /// Calculates the offset from a pointer using wrapping arithmetic.
1399 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1401 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1402 /// offset of `3 * size_of::<T>()` bytes.
1406 /// The resulting pointer does not need to be in bounds, but it is
1407 /// potentially hazardous to dereference (which requires `unsafe`).
1409 /// Always use `.sub(count)` instead when possible, because `sub`
1410 /// allows the compiler to optimize better.
1417 /// // Iterate using a raw pointer in increments of two elements (backwards)
1418 /// let data = [1u8, 2, 3, 4, 5];
1419 /// let mut ptr: *const u8 = data.as_ptr();
1420 /// let start_rounded_down = ptr.wrapping_sub(2);
1421 /// ptr = ptr.wrapping_add(4);
1423 /// // This loop prints "5, 3, 1, "
1424 /// while ptr != start_rounded_down {
1426 /// print!("{}, ", *ptr);
1428 /// ptr = ptr.wrapping_sub(step);
1431 #[stable(feature = "pointer_methods", since = "1.26.0")]
1433 pub fn wrapping_sub(self, count: usize) -> Self
1436 self.wrapping_offset((count as isize).wrapping_neg())
1439 /// Reads the value from `self` without moving it. This leaves the
1440 /// memory in `self` unchanged.
1442 /// See [`ptr::read`] for safety concerns and examples.
1444 /// [`ptr::read`]: ./ptr/fn.read.html
1445 #[stable(feature = "pointer_methods", since = "1.26.0")]
1447 pub unsafe fn read(self) -> T
1453 /// Performs a volatile read of the value from `self` without moving it. This
1454 /// leaves the memory in `self` unchanged.
1456 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1457 /// to not be elided or reordered by the compiler across other volatile
1460 /// See [`ptr::read_volatile`] for safety concerns and examples.
1462 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
1463 #[stable(feature = "pointer_methods", since = "1.26.0")]
1465 pub unsafe fn read_volatile(self) -> T
1471 /// Reads the value from `self` without moving it. This leaves the
1472 /// memory in `self` unchanged.
1474 /// Unlike `read`, the pointer may be unaligned.
1476 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1478 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
1479 #[stable(feature = "pointer_methods", since = "1.26.0")]
1481 pub unsafe fn read_unaligned(self) -> T
1484 read_unaligned(self)
1487 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1488 /// and destination may overlap.
1490 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1492 /// See [`ptr::copy`] for safety concerns and examples.
1494 /// [`ptr::copy`]: ./ptr/fn.copy.html
1495 #[stable(feature = "pointer_methods", since = "1.26.0")]
1497 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1500 copy(self, dest, count)
1503 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1504 /// and destination may *not* overlap.
1506 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1508 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1510 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
1511 #[stable(feature = "pointer_methods", since = "1.26.0")]
1513 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1516 copy_nonoverlapping(self, dest, count)
1519 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1522 /// If it is not possible to align the pointer, the implementation returns
1523 /// `usize::max_value()`.
1525 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1526 /// used with the `offset` or `offset_to` methods.
1528 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
1529 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1530 /// the returned offset is correct in all terms other than alignment.
1534 /// The function panics if `align` is not a power-of-two.
1538 /// Accessing adjacent `u8` as `u16`
1541 /// # fn foo(n: usize) {
1542 /// # use std::mem::align_of;
1544 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1545 /// let ptr = &x[n] as *const u8;
1546 /// let offset = ptr.align_offset(align_of::<u16>());
1547 /// if offset < x.len() - n - 1 {
1548 /// let u16_ptr = ptr.add(offset) as *const u16;
1549 /// assert_ne!(*u16_ptr, 500);
1551 /// // while the pointer can be aligned via `offset`, it would point
1552 /// // outside the allocation
1556 #[stable(feature = "align_offset", since = "1.36.0")]
1557 pub fn align_offset(self, align: usize) -> usize where T: Sized {
1558 if !align.is_power_of_two() {
1559 panic!("align_offset: align is not a power-of-two");
1562 align_offset(self, align)
1569 impl<T: ?Sized> *mut T {
1570 /// Returns `true` if the pointer is null.
1572 /// Note that unsized types have many possible null pointers, as only the
1573 /// raw data pointer is considered, not their length, vtable, etc.
1574 /// Therefore, two pointers that are null may still not compare equal to
1582 /// let mut s = [1, 2, 3];
1583 /// let ptr: *mut u32 = s.as_mut_ptr();
1584 /// assert!(!ptr.is_null());
1586 #[stable(feature = "rust1", since = "1.0.0")]
1588 pub fn is_null(self) -> bool {
1589 // Compare via a cast to a thin pointer, so fat pointers are only
1590 // considering their "data" part for null-ness.
1591 (self as *mut u8) == null_mut()
1594 /// Cast to a pointer to a different type
1595 #[unstable(feature = "ptr_cast", issue = "60602")]
1597 pub const fn cast<U>(self) -> *mut U {
1601 /// Returns `None` if the pointer is null, or else returns a reference to
1602 /// the value wrapped in `Some`.
1606 /// While this method and its mutable counterpart are useful for
1607 /// null-safety, it is important to note that this is still an unsafe
1608 /// operation because the returned value could be pointing to invalid
1611 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1612 /// not necessarily reflect the actual lifetime of the data.
1619 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1622 /// if let Some(val_back) = ptr.as_ref() {
1623 /// println!("We got back the value: {}!", val_back);
1628 /// # Null-unchecked version
1630 /// If you are sure the pointer can never be null and are looking for some kind of
1631 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1632 /// dereference the pointer directly.
1635 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1638 /// let val_back = &*ptr;
1639 /// println!("We got back the value: {}!", val_back);
1642 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1644 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1652 /// Calculates the offset from a pointer.
1654 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1655 /// offset of `3 * size_of::<T>()` bytes.
1659 /// If any of the following conditions are violated, the result is Undefined
1662 /// * Both the starting and resulting pointer must be either in bounds or one
1663 /// byte past the end of the same allocated object.
1665 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1667 /// * The offset being in bounds cannot rely on "wrapping around" the address
1668 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1670 /// The compiler and standard library generally tries to ensure allocations
1671 /// never reach a size where an offset is a concern. For instance, `Vec`
1672 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1673 /// `vec.as_ptr().add(vec.len())` is always safe.
1675 /// Most platforms fundamentally can't even construct such an allocation.
1676 /// For instance, no known 64-bit platform can ever serve a request
1677 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1678 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1679 /// more than `isize::MAX` bytes with things like Physical Address
1680 /// Extension. As such, memory acquired directly from allocators or memory
1681 /// mapped files *may* be too large to handle with this function.
1683 /// Consider using `wrapping_offset` instead if these constraints are
1684 /// difficult to satisfy. The only advantage of this method is that it
1685 /// enables more aggressive compiler optimizations.
1692 /// let mut s = [1, 2, 3];
1693 /// let ptr: *mut u32 = s.as_mut_ptr();
1696 /// println!("{}", *ptr.offset(1));
1697 /// println!("{}", *ptr.offset(2));
1700 #[stable(feature = "rust1", since = "1.0.0")]
1702 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1703 intrinsics::offset(self, count) as *mut T
1706 /// Calculates the offset from a pointer using wrapping arithmetic.
1707 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1708 /// offset of `3 * size_of::<T>()` bytes.
1712 /// The resulting pointer does not need to be in bounds, but it is
1713 /// potentially hazardous to dereference (which requires `unsafe`).
1714 /// In particular, the resulting pointer may *not* be used to access a
1715 /// different allocated object than the one `self` points to. In other
1716 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1717 /// *not* the same as `y`, and dereferencing it is undefined behavior
1718 /// unless `x` and `y` point into the same allocated object.
1720 /// Always use `.offset(count)` instead when possible, because `offset`
1721 /// allows the compiler to optimize better. If you need to cross object
1722 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1729 /// // Iterate using a raw pointer in increments of two elements
1730 /// let mut data = [1u8, 2, 3, 4, 5];
1731 /// let mut ptr: *mut u8 = data.as_mut_ptr();
1733 /// let end_rounded_up = ptr.wrapping_offset(6);
1735 /// while ptr != end_rounded_up {
1739 /// ptr = ptr.wrapping_offset(step);
1741 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1743 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1745 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1747 intrinsics::arith_offset(self, count) as *mut T
1751 /// Returns `None` if the pointer is null, or else returns a mutable
1752 /// reference to the value wrapped in `Some`.
1756 /// As with `as_ref`, this is unsafe because it cannot verify the validity
1757 /// of the returned pointer, nor can it ensure that the lifetime `'a`
1758 /// returned is indeed a valid lifetime for the contained data.
1765 /// let mut s = [1, 2, 3];
1766 /// let ptr: *mut u32 = s.as_mut_ptr();
1767 /// let first_value = unsafe { ptr.as_mut().unwrap() };
1768 /// *first_value = 4;
1769 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1771 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1773 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1781 /// Calculates the distance between two pointers. The returned value is in
1782 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1784 /// This function is the inverse of [`offset`].
1786 /// [`offset`]: #method.offset-1
1787 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
1791 /// If any of the following conditions are violated, the result is Undefined
1794 /// * Both the starting and other pointer must be either in bounds or one
1795 /// byte past the end of the same allocated object.
1797 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1799 /// * The distance between the pointers, in bytes, must be an exact multiple
1800 /// of the size of `T`.
1802 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1804 /// The compiler and standard library generally try to ensure allocations
1805 /// never reach a size where an offset is a concern. For instance, `Vec`
1806 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1807 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1809 /// Most platforms fundamentally can't even construct such an allocation.
1810 /// For instance, no known 64-bit platform can ever serve a request
1811 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1812 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1813 /// more than `isize::MAX` bytes with things like Physical Address
1814 /// Extension. As such, memory acquired directly from allocators or memory
1815 /// mapped files *may* be too large to handle with this function.
1817 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1818 /// difficult to satisfy. The only advantage of this method is that it
1819 /// enables more aggressive compiler optimizations.
1823 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1830 /// #![feature(ptr_offset_from)]
1832 /// let mut a = [0; 5];
1833 /// let ptr1: *mut i32 = &mut a[1];
1834 /// let ptr2: *mut i32 = &mut a[3];
1836 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1837 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1838 /// assert_eq!(ptr1.offset(2), ptr2);
1839 /// assert_eq!(ptr2.offset(-2), ptr1);
1842 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1844 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1845 (self as *const T).offset_from(origin)
1848 /// Calculates the distance between two pointers. The returned value is in
1849 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1851 /// If the address different between the two pointers is not a multiple of
1852 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1855 /// Though this method is safe for any two pointers, note that its result
1856 /// will be mostly useless if the two pointers aren't into the same allocated
1857 /// object, for example if they point to two different local variables.
1861 /// This function panics if `T` is a zero-sized type.
1868 /// #![feature(ptr_wrapping_offset_from)]
1870 /// let mut a = [0; 5];
1871 /// let ptr1: *mut i32 = &mut a[1];
1872 /// let ptr2: *mut i32 = &mut a[3];
1873 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1874 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1875 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1876 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1878 /// let ptr1: *mut i32 = 3 as _;
1879 /// let ptr2: *mut i32 = 13 as _;
1880 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1882 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1884 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1885 (self as *const T).wrapping_offset_from(origin)
1888 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1890 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1891 /// offset of `3 * size_of::<T>()` bytes.
1895 /// If any of the following conditions are violated, the result is Undefined
1898 /// * Both the starting and resulting pointer must be either in bounds or one
1899 /// byte past the end of the same allocated object.
1901 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1903 /// * The offset being in bounds cannot rely on "wrapping around" the address
1904 /// space. That is, the infinite-precision sum must fit in a `usize`.
1906 /// The compiler and standard library generally tries to ensure allocations
1907 /// never reach a size where an offset is a concern. For instance, `Vec`
1908 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1909 /// `vec.as_ptr().add(vec.len())` is always safe.
1911 /// Most platforms fundamentally can't even construct such an allocation.
1912 /// For instance, no known 64-bit platform can ever serve a request
1913 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1914 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1915 /// more than `isize::MAX` bytes with things like Physical Address
1916 /// Extension. As such, memory acquired directly from allocators or memory
1917 /// mapped files *may* be too large to handle with this function.
1919 /// Consider using `wrapping_offset` instead if these constraints are
1920 /// difficult to satisfy. The only advantage of this method is that it
1921 /// enables more aggressive compiler optimizations.
1928 /// let s: &str = "123";
1929 /// let ptr: *const u8 = s.as_ptr();
1932 /// println!("{}", *ptr.add(1) as char);
1933 /// println!("{}", *ptr.add(2) as char);
1936 #[stable(feature = "pointer_methods", since = "1.26.0")]
1938 pub unsafe fn add(self, count: usize) -> Self
1941 self.offset(count as isize)
1944 /// Calculates the offset from a pointer (convenience for
1945 /// `.offset((count as isize).wrapping_neg())`).
1947 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1948 /// offset of `3 * size_of::<T>()` bytes.
1952 /// If any of the following conditions are violated, the result is Undefined
1955 /// * Both the starting and resulting pointer must be either in bounds or one
1956 /// byte past the end of the same allocated object.
1958 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1960 /// * The offset being in bounds cannot rely on "wrapping around" the address
1961 /// space. That is, the infinite-precision sum must fit in a usize.
1963 /// The compiler and standard library generally tries to ensure allocations
1964 /// never reach a size where an offset is a concern. For instance, `Vec`
1965 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1966 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1968 /// Most platforms fundamentally can't even construct such an allocation.
1969 /// For instance, no known 64-bit platform can ever serve a request
1970 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1971 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1972 /// more than `isize::MAX` bytes with things like Physical Address
1973 /// Extension. As such, memory acquired directly from allocators or memory
1974 /// mapped files *may* be too large to handle with this function.
1976 /// Consider using `wrapping_offset` instead if these constraints are
1977 /// difficult to satisfy. The only advantage of this method is that it
1978 /// enables more aggressive compiler optimizations.
1985 /// let s: &str = "123";
1988 /// let end: *const u8 = s.as_ptr().add(3);
1989 /// println!("{}", *end.sub(1) as char);
1990 /// println!("{}", *end.sub(2) as char);
1993 #[stable(feature = "pointer_methods", since = "1.26.0")]
1995 pub unsafe fn sub(self, count: usize) -> Self
1998 self.offset((count as isize).wrapping_neg())
2001 /// Calculates the offset from a pointer using wrapping arithmetic.
2002 /// (convenience for `.wrapping_offset(count as isize)`)
2004 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2005 /// offset of `3 * size_of::<T>()` bytes.
2009 /// The resulting pointer does not need to be in bounds, but it is
2010 /// potentially hazardous to dereference (which requires `unsafe`).
2012 /// Always use `.add(count)` instead when possible, because `add`
2013 /// allows the compiler to optimize better.
2020 /// // Iterate using a raw pointer in increments of two elements
2021 /// let data = [1u8, 2, 3, 4, 5];
2022 /// let mut ptr: *const u8 = data.as_ptr();
2024 /// let end_rounded_up = ptr.wrapping_add(6);
2026 /// // This loop prints "1, 3, 5, "
2027 /// while ptr != end_rounded_up {
2029 /// print!("{}, ", *ptr);
2031 /// ptr = ptr.wrapping_add(step);
2034 #[stable(feature = "pointer_methods", since = "1.26.0")]
2036 pub fn wrapping_add(self, count: usize) -> Self
2039 self.wrapping_offset(count as isize)
2042 /// Calculates the offset from a pointer using wrapping arithmetic.
2043 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
2045 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2046 /// offset of `3 * size_of::<T>()` bytes.
2050 /// The resulting pointer does not need to be in bounds, but it is
2051 /// potentially hazardous to dereference (which requires `unsafe`).
2053 /// Always use `.sub(count)` instead when possible, because `sub`
2054 /// allows the compiler to optimize better.
2061 /// // Iterate using a raw pointer in increments of two elements (backwards)
2062 /// let data = [1u8, 2, 3, 4, 5];
2063 /// let mut ptr: *const u8 = data.as_ptr();
2064 /// let start_rounded_down = ptr.wrapping_sub(2);
2065 /// ptr = ptr.wrapping_add(4);
2067 /// // This loop prints "5, 3, 1, "
2068 /// while ptr != start_rounded_down {
2070 /// print!("{}, ", *ptr);
2072 /// ptr = ptr.wrapping_sub(step);
2075 #[stable(feature = "pointer_methods", since = "1.26.0")]
2077 pub fn wrapping_sub(self, count: usize) -> Self
2080 self.wrapping_offset((count as isize).wrapping_neg())
2083 /// Reads the value from `self` without moving it. This leaves the
2084 /// memory in `self` unchanged.
2086 /// See [`ptr::read`] for safety concerns and examples.
2088 /// [`ptr::read`]: ./ptr/fn.read.html
2089 #[stable(feature = "pointer_methods", since = "1.26.0")]
2091 pub unsafe fn read(self) -> T
2097 /// Performs a volatile read of the value from `self` without moving it. This
2098 /// leaves the memory in `self` unchanged.
2100 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2101 /// to not be elided or reordered by the compiler across other volatile
2104 /// See [`ptr::read_volatile`] for safety concerns and examples.
2106 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
2107 #[stable(feature = "pointer_methods", since = "1.26.0")]
2109 pub unsafe fn read_volatile(self) -> T
2115 /// Reads the value from `self` without moving it. This leaves the
2116 /// memory in `self` unchanged.
2118 /// Unlike `read`, the pointer may be unaligned.
2120 /// See [`ptr::read_unaligned`] for safety concerns and examples.
2122 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
2123 #[stable(feature = "pointer_methods", since = "1.26.0")]
2125 pub unsafe fn read_unaligned(self) -> T
2128 read_unaligned(self)
2131 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2132 /// and destination may overlap.
2134 /// NOTE: this has the *same* argument order as [`ptr::copy`].
2136 /// See [`ptr::copy`] for safety concerns and examples.
2138 /// [`ptr::copy`]: ./ptr/fn.copy.html
2139 #[stable(feature = "pointer_methods", since = "1.26.0")]
2141 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
2144 copy(self, dest, count)
2147 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2148 /// and destination may *not* overlap.
2150 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
2152 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2154 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2155 #[stable(feature = "pointer_methods", since = "1.26.0")]
2157 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
2160 copy_nonoverlapping(self, dest, count)
2163 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2164 /// and destination may overlap.
2166 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
2168 /// See [`ptr::copy`] for safety concerns and examples.
2170 /// [`ptr::copy`]: ./ptr/fn.copy.html
2171 #[stable(feature = "pointer_methods", since = "1.26.0")]
2173 pub unsafe fn copy_from(self, src: *const T, count: usize)
2176 copy(src, self, count)
2179 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2180 /// and destination may *not* overlap.
2182 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
2184 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2186 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2187 #[stable(feature = "pointer_methods", since = "1.26.0")]
2189 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
2192 copy_nonoverlapping(src, self, count)
2195 /// Executes the destructor (if any) of the pointed-to value.
2197 /// See [`ptr::drop_in_place`] for safety concerns and examples.
2199 /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
2200 #[stable(feature = "pointer_methods", since = "1.26.0")]
2202 pub unsafe fn drop_in_place(self) {
2206 /// Overwrites a memory location with the given value without reading or
2207 /// dropping the old value.
2209 /// See [`ptr::write`] for safety concerns and examples.
2211 /// [`ptr::write`]: ./ptr/fn.write.html
2212 #[stable(feature = "pointer_methods", since = "1.26.0")]
2214 pub unsafe fn write(self, val: T)
2220 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
2221 /// bytes of memory starting at `self` to `val`.
2223 /// See [`ptr::write_bytes`] for safety concerns and examples.
2225 /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
2226 #[stable(feature = "pointer_methods", since = "1.26.0")]
2228 pub unsafe fn write_bytes(self, val: u8, count: usize)
2231 write_bytes(self, val, count)
2234 /// Performs a volatile write of a memory location with the given value without
2235 /// reading or dropping the old value.
2237 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2238 /// to not be elided or reordered by the compiler across other volatile
2241 /// See [`ptr::write_volatile`] for safety concerns and examples.
2243 /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
2244 #[stable(feature = "pointer_methods", since = "1.26.0")]
2246 pub unsafe fn write_volatile(self, val: T)
2249 write_volatile(self, val)
2252 /// Overwrites a memory location with the given value without reading or
2253 /// dropping the old value.
2255 /// Unlike `write`, the pointer may be unaligned.
2257 /// See [`ptr::write_unaligned`] for safety concerns and examples.
2259 /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
2260 #[stable(feature = "pointer_methods", since = "1.26.0")]
2262 pub unsafe fn write_unaligned(self, val: T)
2265 write_unaligned(self, val)
2268 /// Replaces the value at `self` with `src`, returning the old
2269 /// value, without dropping either.
2271 /// See [`ptr::replace`] for safety concerns and examples.
2273 /// [`ptr::replace`]: ./ptr/fn.replace.html
2274 #[stable(feature = "pointer_methods", since = "1.26.0")]
2276 pub unsafe fn replace(self, src: T) -> T
2282 /// Swaps the values at two mutable locations of the same type, without
2283 /// deinitializing either. They may overlap, unlike `mem::swap` which is
2284 /// otherwise equivalent.
2286 /// See [`ptr::swap`] for safety concerns and examples.
2288 /// [`ptr::swap`]: ./ptr/fn.swap.html
2289 #[stable(feature = "pointer_methods", since = "1.26.0")]
2291 pub unsafe fn swap(self, with: *mut T)
2297 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
2300 /// If it is not possible to align the pointer, the implementation returns
2301 /// `usize::max_value()`.
2303 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
2304 /// used with the `offset` or `offset_to` methods.
2306 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
2307 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
2308 /// the returned offset is correct in all terms other than alignment.
2312 /// The function panics if `align` is not a power-of-two.
2316 /// Accessing adjacent `u8` as `u16`
2319 /// # fn foo(n: usize) {
2320 /// # use std::mem::align_of;
2322 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
2323 /// let ptr = &x[n] as *const u8;
2324 /// let offset = ptr.align_offset(align_of::<u16>());
2325 /// if offset < x.len() - n - 1 {
2326 /// let u16_ptr = ptr.add(offset) as *const u16;
2327 /// assert_ne!(*u16_ptr, 500);
2329 /// // while the pointer can be aligned via `offset`, it would point
2330 /// // outside the allocation
2334 #[stable(feature = "align_offset", since = "1.36.0")]
2335 pub fn align_offset(self, align: usize) -> usize where T: Sized {
2336 if !align.is_power_of_two() {
2337 panic!("align_offset: align is not a power-of-two");
2340 align_offset(self, align)
2345 /// Align pointer `p`.
2347 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
2348 /// to pointer `p` so that pointer `p` would get aligned to `a`.
2350 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
2351 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2354 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2355 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2356 /// than trying to adapt this to accommodate that change.
2358 /// Any questions go to @nagisa.
2359 #[lang="align_offset"]
2360 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2361 /// Calculate multiplicative modular inverse of `x` modulo `m`.
2363 /// This implementation is tailored for align_offset and has following preconditions:
2365 /// * `m` is a power-of-two;
2366 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2368 /// Implementation of this function shall not panic. Ever.
2370 fn mod_inv(x: usize, m: usize) -> usize {
2371 /// Multiplicative modular inverse table modulo 2⁴ = 16.
2373 /// Note, that this table does not contain values where inverse does not exist (i.e., for
2374 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2375 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2376 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2377 const INV_TABLE_MOD: usize = 16;
2379 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
2381 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
2382 if m <= INV_TABLE_MOD {
2383 table_inverse & (m - 1)
2385 // We iterate "up" using the following formula:
2387 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2389 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
2390 let mut inverse = table_inverse;
2391 let mut going_mod = INV_TABLE_MOD_SQUARED;
2393 // y = y * (2 - xy) mod n
2395 // Note, that we use wrapping operations here intentionally – the original formula
2396 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
2397 // usize::max_value()` instead, because we take the result `mod n` at the end
2399 inverse = inverse.wrapping_mul(
2400 2usize.wrapping_sub(x.wrapping_mul(inverse))
2401 ) & (going_mod - 1);
2403 return inverse & (m - 1);
2405 going_mod = going_mod.wrapping_mul(going_mod);
2410 let stride = mem::size_of::<T>();
2411 let a_minus_one = a.wrapping_sub(1);
2412 let pmoda = p as usize & a_minus_one;
2415 // Already aligned. Yay!
2420 return if stride == 0 {
2421 // If the pointer is not aligned, and the element is zero-sized, then no amount of
2422 // elements will ever align the pointer.
2425 a.wrapping_sub(pmoda)
2429 let smoda = stride & a_minus_one;
2430 // a is power-of-two so cannot be 0. stride = 0 is handled above.
2431 let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
2432 let gcd = 1usize << gcdpow;
2434 if p as usize & (gcd - 1) == 0 {
2435 // This branch solves for the following linear congruence equation:
2437 // $$ p + so ≡ 0 mod a $$
2439 // $p$ here is the pointer value, $s$ – stride of `T`, $o$ offset in `T`s, and $a$ – the
2440 // requested alignment.
2443 // o = (a - (p mod a))/g * ((s/g)⁻¹ mod a)
2445 // The first term is “the relative alignment of p to a”, the second term is “how does
2446 // incrementing p by s bytes change the relative alignment of p”. Division by `g` is
2447 // necessary to make this equation well formed if $a$ and $s$ are not co-prime.
2449 // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
2450 // to take the result $o mod lcm(s, a)$. We can replace $lcm(s, a)$ with just a $a / g$.
2451 let j = a.wrapping_sub(pmoda) >> gcdpow;
2452 let k = smoda >> gcdpow;
2453 return intrinsics::unchecked_rem(j.wrapping_mul(mod_inv(k, a)), a >> gcdpow);
2456 // Cannot be aligned at all.
2462 // Equality for pointers
2463 #[stable(feature = "rust1", since = "1.0.0")]
2464 impl<T: ?Sized> PartialEq for *const T {
2466 fn eq(&self, other: &*const T) -> bool { *self == *other }
2469 #[stable(feature = "rust1", since = "1.0.0")]
2470 impl<T: ?Sized> Eq for *const T {}
2472 #[stable(feature = "rust1", since = "1.0.0")]
2473 impl<T: ?Sized> PartialEq for *mut T {
2475 fn eq(&self, other: &*mut T) -> bool { *self == *other }
2478 #[stable(feature = "rust1", since = "1.0.0")]
2479 impl<T: ?Sized> Eq for *mut T {}
2481 /// Compares raw pointers for equality.
2483 /// This is the same as using the `==` operator, but less generic:
2484 /// the arguments have to be `*const T` raw pointers,
2485 /// not anything that implements `PartialEq`.
2487 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2488 /// by their address rather than comparing the values they point to
2489 /// (which is what the `PartialEq for &T` implementation does).
2497 /// let other_five = 5;
2498 /// let five_ref = &five;
2499 /// let same_five_ref = &five;
2500 /// let other_five_ref = &other_five;
2502 /// assert!(five_ref == same_five_ref);
2503 /// assert!(ptr::eq(five_ref, same_five_ref));
2505 /// assert!(five_ref == other_five_ref);
2506 /// assert!(!ptr::eq(five_ref, other_five_ref));
2509 /// Slices are also compared by their length (fat pointers):
2512 /// let a = [1, 2, 3];
2513 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
2514 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
2515 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
2518 /// Traits are also compared by their implementation:
2521 /// #[repr(transparent)]
2522 /// struct Wrapper { member: i32 }
2525 /// impl Trait for Wrapper {}
2526 /// impl Trait for i32 {}
2529 /// let wrapper = Wrapper { member: 10 };
2531 /// // Pointers have equal addresses.
2532 /// assert!(std::ptr::eq(
2533 /// &wrapper as *const Wrapper as *const u8,
2534 /// &wrapper.member as *const i32 as *const u8
2537 /// // Objects have equal addresses, but `Trait` has different implementations.
2538 /// assert!(!std::ptr::eq(
2539 /// &wrapper as &dyn Trait,
2540 /// &wrapper.member as &dyn Trait,
2542 /// assert!(!std::ptr::eq(
2543 /// &wrapper as &dyn Trait as *const dyn Trait,
2544 /// &wrapper.member as &dyn Trait as *const dyn Trait,
2547 /// // Converting the reference to a `*const u8` compares by address.
2548 /// assert!(std::ptr::eq(
2549 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
2550 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
2554 #[stable(feature = "ptr_eq", since = "1.17.0")]
2556 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2560 /// Hash a raw pointer.
2562 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
2563 /// by its address rather than the value it points to
2564 /// (which is what the `Hash for &T` implementation does).
2569 /// use std::collections::hash_map::DefaultHasher;
2570 /// use std::hash::{Hash, Hasher};
2574 /// let five_ref = &five;
2576 /// let mut hasher = DefaultHasher::new();
2577 /// ptr::hash(five_ref, &mut hasher);
2578 /// let actual = hasher.finish();
2580 /// let mut hasher = DefaultHasher::new();
2581 /// (five_ref as *const i32).hash(&mut hasher);
2582 /// let expected = hasher.finish();
2584 /// assert_eq!(actual, expected);
2586 #[stable(feature = "ptr_hash", since = "1.35.0")]
2587 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
2588 use crate::hash::Hash;
2592 // Impls for function pointers
2593 macro_rules! fnptr_impls_safety_abi {
2594 ($FnTy: ty, $($Arg: ident),*) => {
2595 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2596 impl<Ret, $($Arg),*> PartialEq for $FnTy {
2598 fn eq(&self, other: &Self) -> bool {
2599 *self as usize == *other as usize
2603 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2604 impl<Ret, $($Arg),*> Eq for $FnTy {}
2606 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2607 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2609 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2610 (*self as usize).partial_cmp(&(*other as usize))
2614 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2615 impl<Ret, $($Arg),*> Ord for $FnTy {
2617 fn cmp(&self, other: &Self) -> Ordering {
2618 (*self as usize).cmp(&(*other as usize))
2622 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2623 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2624 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2625 state.write_usize(*self as usize)
2629 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2630 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2631 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2632 fmt::Pointer::fmt(&(*self as *const ()), f)
2636 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2637 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2638 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2639 fmt::Pointer::fmt(&(*self as *const ()), f)
2645 macro_rules! fnptr_impls_args {
2646 ($($Arg: ident),+) => {
2647 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2648 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2649 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2650 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2651 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2652 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2655 // No variadic functions with 0 parameters
2656 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2657 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2658 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2659 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2663 fnptr_impls_args! { }
2664 fnptr_impls_args! { A }
2665 fnptr_impls_args! { A, B }
2666 fnptr_impls_args! { A, B, C }
2667 fnptr_impls_args! { A, B, C, D }
2668 fnptr_impls_args! { A, B, C, D, E }
2669 fnptr_impls_args! { A, B, C, D, E, F }
2670 fnptr_impls_args! { A, B, C, D, E, F, G }
2671 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2672 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2673 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2674 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2675 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2677 // Comparison for pointers
2678 #[stable(feature = "rust1", since = "1.0.0")]
2679 impl<T: ?Sized> Ord for *const T {
2681 fn cmp(&self, other: &*const T) -> Ordering {
2684 } else if self == other {
2692 #[stable(feature = "rust1", since = "1.0.0")]
2693 impl<T: ?Sized> PartialOrd for *const T {
2695 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2696 Some(self.cmp(other))
2700 fn lt(&self, other: &*const T) -> bool { *self < *other }
2703 fn le(&self, other: &*const T) -> bool { *self <= *other }
2706 fn gt(&self, other: &*const T) -> bool { *self > *other }
2709 fn ge(&self, other: &*const T) -> bool { *self >= *other }
2712 #[stable(feature = "rust1", since = "1.0.0")]
2713 impl<T: ?Sized> Ord for *mut T {
2715 fn cmp(&self, other: &*mut T) -> Ordering {
2718 } else if self == other {
2726 #[stable(feature = "rust1", since = "1.0.0")]
2727 impl<T: ?Sized> PartialOrd for *mut T {
2729 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2730 Some(self.cmp(other))
2734 fn lt(&self, other: &*mut T) -> bool { *self < *other }
2737 fn le(&self, other: &*mut T) -> bool { *self <= *other }
2740 fn gt(&self, other: &*mut T) -> bool { *self > *other }
2743 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
2746 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
2747 /// of this wrapper owns the referent. Useful for building abstractions like
2748 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
2750 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
2751 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
2752 /// the kind of strong aliasing guarantees an instance of `T` can expect:
2753 /// the referent of the pointer should not be modified without a unique path to
2754 /// its owning Unique.
2756 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
2757 /// consider using `NonNull`, which has weaker semantics.
2759 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2760 /// is never dereferenced. This is so that enums may use this forbidden value
2761 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
2762 /// However the pointer may still dangle if it isn't dereferenced.
2764 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
2765 /// for any type which upholds Unique's aliasing requirements.
2766 #[unstable(feature = "ptr_internals", issue = "0",
2767 reason = "use NonNull instead and consider PhantomData<T> \
2768 (if you also use #[may_dangle]), Send, and/or Sync")]
2770 #[repr(transparent)]
2771 #[rustc_layout_scalar_valid_range_start(1)]
2772 pub struct Unique<T: ?Sized> {
2774 // NOTE: this marker has no consequences for variance, but is necessary
2775 // for dropck to understand that we logically own a `T`.
2777 // For details, see:
2778 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
2779 _marker: PhantomData<T>,
2782 #[unstable(feature = "ptr_internals", issue = "0")]
2783 impl<T: ?Sized> fmt::Debug for Unique<T> {
2784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2785 fmt::Pointer::fmt(&self.as_ptr(), f)
2789 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
2790 /// reference is unaliased. Note that this aliasing invariant is
2791 /// unenforced by the type system; the abstraction using the
2792 /// `Unique` must enforce it.
2793 #[unstable(feature = "ptr_internals", issue = "0")]
2794 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
2796 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
2797 /// reference is unaliased. Note that this aliasing invariant is
2798 /// unenforced by the type system; the abstraction using the
2799 /// `Unique` must enforce it.
2800 #[unstable(feature = "ptr_internals", issue = "0")]
2801 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
2803 #[unstable(feature = "ptr_internals", issue = "0")]
2804 impl<T: Sized> Unique<T> {
2805 /// Creates a new `Unique` that is dangling, but well-aligned.
2807 /// This is useful for initializing types which lazily allocate, like
2808 /// `Vec::new` does.
2810 /// Note that the pointer value may potentially represent a valid pointer to
2811 /// a `T`, which means this must not be used as a "not yet initialized"
2812 /// sentinel value. Types that lazily allocate must track initialization by
2813 /// some other means.
2814 // FIXME: rename to dangling() to match NonNull?
2815 pub const fn empty() -> Self {
2817 Unique::new_unchecked(mem::align_of::<T>() as *mut T)
2822 #[unstable(feature = "ptr_internals", issue = "0")]
2823 impl<T: ?Sized> Unique<T> {
2824 /// Creates a new `Unique`.
2828 /// `ptr` must be non-null.
2829 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2830 Unique { pointer: ptr as _, _marker: PhantomData }
2833 /// Creates a new `Unique` if `ptr` is non-null.
2834 pub fn new(ptr: *mut T) -> Option<Self> {
2836 Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
2842 /// Acquires the underlying `*mut` pointer.
2843 pub const fn as_ptr(self) -> *mut T {
2844 self.pointer as *mut T
2847 /// Dereferences the content.
2849 /// The resulting lifetime is bound to self so this behaves "as if"
2850 /// it were actually an instance of T that is getting borrowed. If a longer
2851 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2852 pub unsafe fn as_ref(&self) -> &T {
2856 /// Mutably dereferences the content.
2858 /// The resulting lifetime is bound to self so this behaves "as if"
2859 /// it were actually an instance of T that is getting borrowed. If a longer
2860 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2861 pub unsafe fn as_mut(&mut self) -> &mut T {
2866 #[unstable(feature = "ptr_internals", issue = "0")]
2867 impl<T: ?Sized> Clone for Unique<T> {
2868 fn clone(&self) -> Self {
2873 #[unstable(feature = "ptr_internals", issue = "0")]
2874 impl<T: ?Sized> Copy for Unique<T> { }
2876 #[unstable(feature = "ptr_internals", issue = "0")]
2877 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
2879 #[unstable(feature = "ptr_internals", issue = "0")]
2880 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> { }
2882 #[unstable(feature = "ptr_internals", issue = "0")]
2883 impl<T: ?Sized> fmt::Pointer for Unique<T> {
2884 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2885 fmt::Pointer::fmt(&self.as_ptr(), f)
2889 #[unstable(feature = "ptr_internals", issue = "0")]
2890 impl<T: ?Sized> From<&mut T> for Unique<T> {
2891 fn from(reference: &mut T) -> Self {
2892 unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
2896 #[unstable(feature = "ptr_internals", issue = "0")]
2897 impl<T: ?Sized> From<&T> for Unique<T> {
2898 fn from(reference: &T) -> Self {
2899 unsafe { Unique { pointer: reference as *const T, _marker: PhantomData } }
2903 #[unstable(feature = "ptr_internals", issue = "0")]
2904 impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
2905 fn from(p: NonNull<T>) -> Self {
2906 unsafe { Unique { pointer: p.pointer, _marker: PhantomData } }
2910 /// `*mut T` but non-zero and covariant.
2912 /// This is often the correct thing to use when building data structures using
2913 /// raw pointers, but is ultimately more dangerous to use because of its additional
2914 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
2916 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2917 /// is never dereferenced. This is so that enums may use this forbidden value
2918 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
2919 /// However the pointer may still dangle if it isn't dereferenced.
2921 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
2922 /// for your use case, you should include some [`PhantomData`] in your type to
2923 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
2924 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
2925 /// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they
2926 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
2928 /// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
2929 /// not change the fact that mutating through a (pointer derived from a) shared
2930 /// reference is undefined behavior unless the mutation happens inside an
2931 /// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
2932 /// reference. When using this `From` instance without an `UnsafeCell<T>`,
2933 /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
2934 /// is never used for mutation.
2936 /// [`PhantomData`]: ../marker/struct.PhantomData.html
2937 /// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
2938 #[stable(feature = "nonnull", since = "1.25.0")]
2939 #[repr(transparent)]
2940 #[rustc_layout_scalar_valid_range_start(1)]
2941 pub struct NonNull<T: ?Sized> {
2945 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
2946 // N.B., this impl is unnecessary, but should provide better error messages.
2947 #[stable(feature = "nonnull", since = "1.25.0")]
2948 impl<T: ?Sized> !Send for NonNull<T> { }
2950 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
2951 // N.B., this impl is unnecessary, but should provide better error messages.
2952 #[stable(feature = "nonnull", since = "1.25.0")]
2953 impl<T: ?Sized> !Sync for NonNull<T> { }
2955 impl<T: Sized> NonNull<T> {
2956 /// Creates a new `NonNull` that is dangling, but well-aligned.
2958 /// This is useful for initializing types which lazily allocate, like
2959 /// `Vec::new` does.
2961 /// Note that the pointer value may potentially represent a valid pointer to
2962 /// a `T`, which means this must not be used as a "not yet initialized"
2963 /// sentinel value. Types that lazily allocate must track initialization by
2964 /// some other means.
2965 #[stable(feature = "nonnull", since = "1.25.0")]
2967 pub const fn dangling() -> Self {
2969 let ptr = mem::align_of::<T>() as *mut T;
2970 NonNull::new_unchecked(ptr)
2975 impl<T: ?Sized> NonNull<T> {
2976 /// Creates a new `NonNull`.
2980 /// `ptr` must be non-null.
2981 #[stable(feature = "nonnull", since = "1.25.0")]
2983 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2984 NonNull { pointer: ptr as _ }
2987 /// Creates a new `NonNull` if `ptr` is non-null.
2988 #[stable(feature = "nonnull", since = "1.25.0")]
2990 pub fn new(ptr: *mut T) -> Option<Self> {
2992 Some(unsafe { Self::new_unchecked(ptr) })
2998 /// Acquires the underlying `*mut` pointer.
2999 #[stable(feature = "nonnull", since = "1.25.0")]
3001 pub const fn as_ptr(self) -> *mut T {
3002 self.pointer as *mut T
3005 /// Dereferences the content.
3007 /// The resulting lifetime is bound to self so this behaves "as if"
3008 /// it were actually an instance of T that is getting borrowed. If a longer
3009 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
3010 #[stable(feature = "nonnull", since = "1.25.0")]
3012 pub unsafe fn as_ref(&self) -> &T {
3016 /// Mutably dereferences the content.
3018 /// The resulting lifetime is bound to self so this behaves "as if"
3019 /// it were actually an instance of T that is getting borrowed. If a longer
3020 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
3021 #[stable(feature = "nonnull", since = "1.25.0")]
3023 pub unsafe fn as_mut(&mut self) -> &mut T {
3027 /// Cast to a pointer of another type
3028 #[stable(feature = "nonnull_cast", since = "1.27.0")]
3030 pub const fn cast<U>(self) -> NonNull<U> {
3032 NonNull::new_unchecked(self.as_ptr() as *mut U)
3037 #[stable(feature = "nonnull", since = "1.25.0")]
3038 impl<T: ?Sized> Clone for NonNull<T> {
3039 fn clone(&self) -> Self {
3044 #[stable(feature = "nonnull", since = "1.25.0")]
3045 impl<T: ?Sized> Copy for NonNull<T> { }
3047 #[unstable(feature = "coerce_unsized", issue = "27732")]
3048 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
3050 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
3051 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
3053 #[stable(feature = "nonnull", since = "1.25.0")]
3054 impl<T: ?Sized> fmt::Debug for NonNull<T> {
3055 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3056 fmt::Pointer::fmt(&self.as_ptr(), f)
3060 #[stable(feature = "nonnull", since = "1.25.0")]
3061 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
3062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3063 fmt::Pointer::fmt(&self.as_ptr(), f)
3067 #[stable(feature = "nonnull", since = "1.25.0")]
3068 impl<T: ?Sized> Eq for NonNull<T> {}
3070 #[stable(feature = "nonnull", since = "1.25.0")]
3071 impl<T: ?Sized> PartialEq for NonNull<T> {
3073 fn eq(&self, other: &Self) -> bool {
3074 self.as_ptr() == other.as_ptr()
3078 #[stable(feature = "nonnull", since = "1.25.0")]
3079 impl<T: ?Sized> Ord for NonNull<T> {
3081 fn cmp(&self, other: &Self) -> Ordering {
3082 self.as_ptr().cmp(&other.as_ptr())
3086 #[stable(feature = "nonnull", since = "1.25.0")]
3087 impl<T: ?Sized> PartialOrd for NonNull<T> {
3089 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3090 self.as_ptr().partial_cmp(&other.as_ptr())
3094 #[stable(feature = "nonnull", since = "1.25.0")]
3095 impl<T: ?Sized> hash::Hash for NonNull<T> {
3097 fn hash<H: hash::Hasher>(&self, state: &mut H) {
3098 self.as_ptr().hash(state)
3102 #[unstable(feature = "ptr_internals", issue = "0")]
3103 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
3105 fn from(unique: Unique<T>) -> Self {
3106 unsafe { NonNull { pointer: unique.pointer } }
3110 #[stable(feature = "nonnull", since = "1.25.0")]
3111 impl<T: ?Sized> From<&mut T> for NonNull<T> {
3113 fn from(reference: &mut T) -> Self {
3114 unsafe { NonNull { pointer: reference as *mut T } }
3118 #[stable(feature = "nonnull", since = "1.25.0")]
3119 impl<T: ?Sized> From<&T> for NonNull<T> {
3121 fn from(reference: &T) -> Self {
3122 unsafe { NonNull { pointer: reference as *const T } }