1 //! Manually manage memory through raw pointers.
3 //! *[See also the pointer primitive types](pointer).*
7 //! Many functions in this module take raw pointers as arguments and read from
8 //! or write to them. For this to be safe, these pointers must be *valid*.
9 //! Whether a pointer is valid depends on the operation it is used for
10 //! (read or write), and the extent of the memory that is accessed (i.e.,
11 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
12 //! to access only a single value, in which case the documentation omits the size
13 //! and implicitly assumes it to be `size_of::<T>()` bytes.
15 //! The precise rules for validity are not determined yet. The guarantees that are
16 //! provided at this point are very minimal:
18 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
19 //! * For a pointer to be valid, it is necessary, but not always sufficient, that the pointer
20 //! be *dereferenceable*: the memory range of the given size starting at the pointer must all be
21 //! within the bounds of a single allocated object. Note that in Rust,
22 //! every (stack-allocated) variable is considered a separate allocated object.
23 //! * Even for operations of [size zero][zst], the pointer must not be pointing to deallocated
24 //! memory, i.e., deallocation makes pointers invalid even for zero-sized operations. However,
25 //! casting any non-zero integer *literal* to a pointer is valid for zero-sized accesses, even if
26 //! some memory happens to exist at that address and gets deallocated. This corresponds to writing
27 //! your own allocator: allocating zero-sized objects is not very hard. The canonical way to
28 //! obtain a pointer that is valid for zero-sized accesses is [`NonNull::dangling`].
29 //! * All accesses performed by functions in this module are *non-atomic* in the sense
30 //! of [atomic operations] used to synchronize between threads. This means it is
31 //! undefined behavior to perform two concurrent accesses to the same location from different
32 //! threads unless both accesses only read from memory. Notice that this explicitly
33 //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
34 //! be used for inter-thread synchronization.
35 //! * The result of casting a reference to a pointer is valid for as long as the
36 //! underlying object is live and no reference (just raw pointers) is used to
37 //! access the same memory.
39 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
40 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
41 //! will be provided eventually, as the [aliasing] rules are being determined. For more
42 //! information, see the [book] as well as the section in the reference devoted
43 //! to [undefined behavior][ub].
47 //! Valid raw pointers as defined above are not necessarily properly aligned (where
48 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
49 //! aligned to `mem::align_of::<T>()`). However, most functions require their
50 //! arguments to be properly aligned, and will explicitly state
51 //! this requirement in their documentation. Notable exceptions to this are
52 //! [`read_unaligned`] and [`write_unaligned`].
54 //! When a function requires proper alignment, it does so even if the access
55 //! has size 0, i.e., even if memory is not actually touched. Consider using
56 //! [`NonNull::dangling`] in such cases.
58 //! ## Allocated object
60 //! For several operations, such as [`offset`] or field projections (`expr.field`), the notion of an
61 //! "allocated object" becomes relevant. An allocated object is a contiguous region of memory.
62 //! Common examples of allocated objects include stack-allocated variables (each variable is a
63 //! separate allocated object), heap allocations (each allocation created by the global allocator is
64 //! a separate allocated object), and `static` variables.
66 //! [aliasing]: ../../nomicon/aliasing.html
67 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
68 //! [ub]: ../../reference/behavior-considered-undefined.html
69 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
70 //! [atomic operations]: crate::sync::atomic
71 //! [`offset`]: pointer::offset
73 #![stable(feature = "rust1", since = "1.0.0")]
75 use crate::cmp::Ordering;
78 use crate::intrinsics::{self, abort, is_aligned_and_not_null};
79 use crate::mem::{self, MaybeUninit};
81 #[stable(feature = "rust1", since = "1.0.0")]
83 pub use crate::intrinsics::copy_nonoverlapping;
85 #[stable(feature = "rust1", since = "1.0.0")]
87 pub use crate::intrinsics::copy;
89 #[stable(feature = "rust1", since = "1.0.0")]
91 pub use crate::intrinsics::write_bytes;
94 pub(crate) use metadata::PtrRepr;
95 #[unstable(feature = "ptr_metadata", issue = "81513")]
96 pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin};
99 #[stable(feature = "nonnull", since = "1.25.0")]
100 pub use non_null::NonNull;
103 #[unstable(feature = "ptr_internals", issue = "none")]
104 pub use unique::Unique;
109 /// Executes the destructor (if any) of the pointed-to value.
111 /// This is semantically equivalent to calling [`ptr::read`] and discarding
112 /// the result, but has the following advantages:
114 /// * It is *required* to use `drop_in_place` to drop unsized types like
115 /// trait objects, because they can't be read out onto the stack and
116 /// dropped normally.
118 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
119 /// dropping manually allocated memory (e.g., in the implementations of
120 /// `Box`/`Rc`/`Vec`), as the compiler doesn't need to prove that it's
121 /// sound to elide the copy.
123 /// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
124 /// (pinned data must not be moved before it is dropped).
126 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
127 /// location first using [`ptr::read_unaligned`]. For packed structs, this move is
128 /// done automatically by the compiler. This means the fields of packed structs
129 /// are not dropped in-place.
131 /// [`ptr::read`]: self::read
132 /// [`ptr::read_unaligned`]: self::read_unaligned
133 /// [pinned]: crate::pin
137 /// Behavior is undefined if any of the following conditions are violated:
139 /// * `to_drop` must be [valid] for both reads and writes.
141 /// * `to_drop` must be properly aligned.
143 /// * The value `to_drop` points to must be valid for dropping, which may mean it must uphold
144 /// additional invariants - this is type-dependent.
146 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
147 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
148 /// foo` counts as a use because it will cause the value to be dropped
149 /// again. [`write()`] can be used to overwrite data without causing it to be
152 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
154 /// [valid]: self#safety
158 /// Manually remove the last item from a vector:
164 /// let last = Rc::new(1);
165 /// let weak = Rc::downgrade(&last);
167 /// let mut v = vec![Rc::new(0), last];
170 /// // Get a raw pointer to the last element in `v`.
171 /// let ptr = &mut v[1] as *mut _;
172 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
173 /// // to prevent issues if the `drop_in_place` below panics.
175 /// // Without a call `drop_in_place`, the last item would never be dropped,
176 /// // and the memory it manages would be leaked.
177 /// ptr::drop_in_place(ptr);
180 /// assert_eq!(v, &[0.into()]);
182 /// // Ensure that the last item was dropped.
183 /// assert!(weak.upgrade().is_none());
185 #[stable(feature = "drop_in_place", since = "1.8.0")]
186 #[lang = "drop_in_place"]
187 #[allow(unconditional_recursion)]
188 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
189 // Code here does not matter - this is replaced by the
190 // real drop glue by the compiler.
192 // SAFETY: see comment above
193 unsafe { drop_in_place(to_drop) }
196 /// Creates a null raw pointer.
203 /// let p: *const i32 = ptr::null();
204 /// assert!(p.is_null());
208 #[stable(feature = "rust1", since = "1.0.0")]
210 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
211 #[rustc_diagnostic_item = "ptr_null"]
212 pub const fn null<T>() -> *const T {
216 /// Creates a null mutable raw pointer.
223 /// let p: *mut i32 = ptr::null_mut();
224 /// assert!(p.is_null());
228 #[stable(feature = "rust1", since = "1.0.0")]
230 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
231 #[rustc_diagnostic_item = "ptr_null_mut"]
232 pub const fn null_mut<T>() -> *mut T {
236 /// Forms a raw slice from a pointer and a length.
238 /// The `len` argument is the number of **elements**, not the number of bytes.
240 /// This function is safe, but actually using the return value is unsafe.
241 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
243 /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
250 /// // create a slice pointer when starting out with a pointer to the first element
251 /// let x = [5, 6, 7];
252 /// let raw_pointer = x.as_ptr();
253 /// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
254 /// assert_eq!(unsafe { &*slice }[2], 7);
257 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
258 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
259 pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
260 from_raw_parts(data.cast(), len)
263 /// Performs the same functionality as [`slice_from_raw_parts`], except that a
264 /// raw mutable slice is returned, as opposed to a raw immutable slice.
266 /// See the documentation of [`slice_from_raw_parts`] for more details.
268 /// This function is safe, but actually using the return value is unsafe.
269 /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
271 /// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
278 /// let x = &mut [5, 6, 7];
279 /// let raw_pointer = x.as_mut_ptr();
280 /// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
283 /// (*slice)[2] = 99; // assign a value at an index in the slice
286 /// assert_eq!(unsafe { &*slice }[2], 99);
289 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
290 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
291 pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
292 from_raw_parts_mut(data.cast(), len)
295 /// Swaps the values at two mutable locations of the same type, without
296 /// deinitializing either.
298 /// But for the following two exceptions, this function is semantically
299 /// equivalent to [`mem::swap`]:
301 /// * It operates on raw pointers instead of references. When references are
302 /// available, [`mem::swap`] should be preferred.
304 /// * The two pointed-to values may overlap. If the values do overlap, then the
305 /// overlapping region of memory from `x` will be used. This is demonstrated
306 /// in the second example below.
310 /// Behavior is undefined if any of the following conditions are violated:
312 /// * Both `x` and `y` must be [valid] for both reads and writes.
314 /// * Both `x` and `y` must be properly aligned.
316 /// Note that even if `T` has size `0`, the pointers must be non-null and properly aligned.
318 /// [valid]: self#safety
322 /// Swapping two non-overlapping regions:
327 /// let mut array = [0, 1, 2, 3];
329 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
330 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
334 /// assert_eq!([2, 3, 0, 1], array);
338 /// Swapping two overlapping regions:
343 /// let mut array: [i32; 4] = [0, 1, 2, 3];
345 /// let array_ptr: *mut i32 = array.as_mut_ptr();
347 /// let x = array_ptr as *mut [i32; 3]; // this is `array[0..3]`
348 /// let y = unsafe { array_ptr.add(1) } as *mut [i32; 3]; // this is `array[1..4]`
352 /// // The indices `1..3` of the slice overlap between `x` and `y`.
353 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
354 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
355 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
356 /// // This implementation is defined to make the latter choice.
357 /// assert_eq!([1, 0, 1, 2], array);
361 #[stable(feature = "rust1", since = "1.0.0")]
362 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
363 pub const unsafe fn swap<T>(x: *mut T, y: *mut T) {
364 // Give ourselves some scratch space to work with.
365 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
366 let mut tmp = MaybeUninit::<T>::uninit();
369 // SAFETY: the caller must guarantee that `x` and `y` are
370 // valid for writes and properly aligned. `tmp` cannot be
371 // overlapping either `x` or `y` because `tmp` was just allocated
372 // on the stack as a separate allocated object.
374 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
375 copy(y, x, 1); // `x` and `y` may overlap
376 copy_nonoverlapping(tmp.as_ptr(), y, 1);
380 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
381 /// beginning at `x` and `y`. The two regions must *not* overlap.
385 /// Behavior is undefined if any of the following conditions are violated:
387 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
388 /// size_of::<T>()` bytes.
390 /// * Both `x` and `y` must be properly aligned.
392 /// * The region of memory beginning at `x` with a size of `count *
393 /// size_of::<T>()` bytes must *not* overlap with the region of memory
394 /// beginning at `y` with the same size.
396 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
397 /// the pointers must be non-null and properly aligned.
399 /// [valid]: self#safety
408 /// let mut x = [1, 2, 3, 4];
409 /// let mut y = [7, 8, 9];
412 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
415 /// assert_eq!(x, [7, 8, 3, 4]);
416 /// assert_eq!(y, [1, 2, 9]);
419 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
420 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
421 pub const unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
423 macro_rules! attempt_swap_as_chunks {
425 if mem::align_of::<T>() >= mem::align_of::<$ChunkTy>()
426 && mem::size_of::<T>() % mem::size_of::<$ChunkTy>() == 0
428 let x: *mut MaybeUninit<$ChunkTy> = x.cast();
429 let y: *mut MaybeUninit<$ChunkTy> = y.cast();
430 let count = count * (mem::size_of::<T>() / mem::size_of::<$ChunkTy>());
431 // SAFETY: these are the same bytes that the caller promised were
432 // ok, just typed as `MaybeUninit<ChunkTy>`s instead of as `T`s.
433 // The `if` condition above ensures that we're not violating
434 // alignment requirements, and that the division is exact so
435 // that we don't lose any bytes off the end.
436 return unsafe { swap_nonoverlapping_simple(x, y, count) };
441 // NOTE(scottmcm) MIRI is disabled here as reading in smaller units is a
442 // pessimization for it. Also, if the type contains any unaligned pointers,
443 // copying those over multiple reads is difficult to support.
446 // Split up the slice into small power-of-two-sized chunks that LLVM is able
447 // to vectorize (unless it's a special type with more-than-pointer alignment,
448 // because we don't want to pessimize things like slices of SIMD vectors.)
449 if mem::align_of::<T>() <= mem::size_of::<usize>()
450 && (!mem::size_of::<T>().is_power_of_two()
451 || mem::size_of::<T>() > mem::size_of::<usize>() * 2)
453 attempt_swap_as_chunks!(usize);
454 attempt_swap_as_chunks!(u8);
458 // SAFETY: Same preconditions as this function
459 unsafe { swap_nonoverlapping_simple(x, y, count) }
462 /// Same behaviour and safety conditions as [`swap_nonoverlapping`]
464 /// LLVM can vectorize this (at least it can for the power-of-two-sized types
465 /// `swap_nonoverlapping` tries to use) so no need to manually SIMD it.
467 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
468 const unsafe fn swap_nonoverlapping_simple<T>(x: *mut T, y: *mut T, count: usize) {
472 // SAFETY: By precondition, `i` is in-bounds because it's below `n`
473 unsafe { &mut *x.add(i) };
475 // SAFETY: By precondition, `i` is in-bounds because it's below `n`
476 // and it's distinct from `x` since the ranges are non-overlapping
477 unsafe { &mut *y.add(i) };
478 mem::swap_simple(x, y);
484 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
486 /// Neither value is dropped.
488 /// This function is semantically equivalent to [`mem::replace`] except that it
489 /// operates on raw pointers instead of references. When references are
490 /// available, [`mem::replace`] should be preferred.
494 /// Behavior is undefined if any of the following conditions are violated:
496 /// * `dst` must be [valid] for both reads and writes.
498 /// * `dst` must be properly aligned.
500 /// * `dst` must point to a properly initialized value of type `T`.
502 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
504 /// [valid]: self#safety
511 /// let mut rust = vec!['b', 'u', 's', 't'];
513 /// // `mem::replace` would have the same effect without requiring the unsafe
516 /// ptr::replace(&mut rust[0], 'r')
519 /// assert_eq!(b, 'b');
520 /// assert_eq!(rust, &['r', 'u', 's', 't']);
523 #[stable(feature = "rust1", since = "1.0.0")]
524 #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
525 pub const unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
526 // SAFETY: the caller must guarantee that `dst` is valid to be
527 // cast to a mutable reference (valid for writes, aligned, initialized),
528 // and cannot overlap `src` since `dst` must point to a distinct
531 mem::swap(&mut *dst, &mut src); // cannot overlap
536 /// Reads the value from `src` without moving it. This leaves the
537 /// memory in `src` unchanged.
541 /// Behavior is undefined if any of the following conditions are violated:
543 /// * `src` must be [valid] for reads.
545 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
548 /// * `src` must point to a properly initialized value of type `T`.
550 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
558 /// let y = &x as *const i32;
561 /// assert_eq!(std::ptr::read(y), 12);
565 /// Manually implement [`mem::swap`]:
570 /// fn swap<T>(a: &mut T, b: &mut T) {
572 /// // Create a bitwise copy of the value at `a` in `tmp`.
573 /// let tmp = ptr::read(a);
575 /// // Exiting at this point (either by explicitly returning or by
576 /// // calling a function which panics) would cause the value in `tmp` to
577 /// // be dropped while the same value is still referenced by `a`. This
578 /// // could trigger undefined behavior if `T` is not `Copy`.
580 /// // Create a bitwise copy of the value at `b` in `a`.
581 /// // This is safe because mutable references cannot alias.
582 /// ptr::copy_nonoverlapping(b, a, 1);
584 /// // As above, exiting here could trigger undefined behavior because
585 /// // the same value is referenced by `a` and `b`.
587 /// // Move `tmp` into `b`.
588 /// ptr::write(b, tmp);
590 /// // `tmp` has been moved (`write` takes ownership of its second argument),
591 /// // so nothing is dropped implicitly here.
595 /// let mut foo = "foo".to_owned();
596 /// let mut bar = "bar".to_owned();
598 /// swap(&mut foo, &mut bar);
600 /// assert_eq!(foo, "bar");
601 /// assert_eq!(bar, "foo");
604 /// ## Ownership of the Returned Value
606 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
607 /// If `T` is not [`Copy`], using both the returned value and the value at
608 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
609 /// use because it will attempt to drop the value at `*src`.
611 /// [`write()`] can be used to overwrite data without causing it to be dropped.
616 /// let mut s = String::from("foo");
618 /// // `s2` now points to the same underlying memory as `s`.
619 /// let mut s2: String = ptr::read(&s);
621 /// assert_eq!(s2, "foo");
623 /// // Assigning to `s2` causes its original value to be dropped. Beyond
624 /// // this point, `s` must no longer be used, as the underlying memory has
626 /// s2 = String::default();
627 /// assert_eq!(s2, "");
629 /// // Assigning to `s` would cause the old value to be dropped again,
630 /// // resulting in undefined behavior.
631 /// // s = String::from("bar"); // ERROR
633 /// // `ptr::write` can be used to overwrite a value without dropping it.
634 /// ptr::write(&mut s, String::from("bar"));
637 /// assert_eq!(s, "bar");
640 /// [valid]: self#safety
642 #[stable(feature = "rust1", since = "1.0.0")]
643 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
644 pub const unsafe fn read<T>(src: *const T) -> T {
645 // We are calling the intrinsics directly to avoid function calls in the generated code
646 // as `intrinsics::copy_nonoverlapping` is a wrapper function.
647 extern "rust-intrinsic" {
648 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
649 fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
652 let mut tmp = MaybeUninit::<T>::uninit();
653 // SAFETY: the caller must guarantee that `src` is valid for reads.
654 // `src` cannot overlap `tmp` because `tmp` was just allocated on
655 // the stack as a separate allocated object.
657 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
658 // to be properly initialized.
660 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
665 /// Reads the value from `src` without moving it. This leaves the
666 /// memory in `src` unchanged.
668 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
672 /// Behavior is undefined if any of the following conditions are violated:
674 /// * `src` must be [valid] for reads.
676 /// * `src` must point to a properly initialized value of type `T`.
678 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
679 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
680 /// value and the value at `*src` can [violate memory safety][read-ownership].
682 /// Note that even if `T` has size `0`, the pointer must be non-null.
684 /// [read-ownership]: read#ownership-of-the-returned-value
685 /// [valid]: self#safety
687 /// ## On `packed` structs
689 /// Attempting to create a raw pointer to an `unaligned` struct field with
690 /// an expression such as `&packed.unaligned as *const FieldType` creates an
691 /// intermediate unaligned reference before converting that to a raw pointer.
692 /// That this reference is temporary and immediately cast is inconsequential
693 /// as the compiler always expects references to be properly aligned.
694 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
695 /// *undefined behavior* in your program.
697 /// Instead you must use the [`ptr::addr_of!`](addr_of) macro to
698 /// create the pointer. You may use that returned pointer together with this
701 /// An example of what not to do and how this relates to `read_unaligned` is:
704 /// #[repr(packed, C)]
710 /// let packed = Packed {
712 /// unaligned: 0x01020304,
715 /// // Take the address of a 32-bit integer which is not aligned.
716 /// // In contrast to `&packed.unaligned as *const _`, this has no undefined behavior.
717 /// let unaligned = std::ptr::addr_of!(packed.unaligned);
719 /// let v = unsafe { std::ptr::read_unaligned(unaligned) };
720 /// assert_eq!(v, 0x01020304);
723 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
727 /// Read a usize value from a byte buffer:
732 /// fn read_usize(x: &[u8]) -> usize {
733 /// assert!(x.len() >= mem::size_of::<usize>());
735 /// let ptr = x.as_ptr() as *const usize;
737 /// unsafe { ptr.read_unaligned() }
741 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
742 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
743 pub const unsafe fn read_unaligned<T>(src: *const T) -> T {
744 let mut tmp = MaybeUninit::<T>::uninit();
745 // SAFETY: the caller must guarantee that `src` is valid for reads.
746 // `src` cannot overlap `tmp` because `tmp` was just allocated on
747 // the stack as a separate allocated object.
749 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
750 // to be properly initialized.
752 copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::<T>());
757 /// Overwrites a memory location with the given value without reading or
758 /// dropping the old value.
760 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
761 /// allocations or resources, so care should be taken not to overwrite an object
762 /// that should be dropped.
764 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
765 /// location pointed to by `dst`.
767 /// This is appropriate for initializing uninitialized memory, or overwriting
768 /// memory that has previously been [`read`] from.
772 /// Behavior is undefined if any of the following conditions are violated:
774 /// * `dst` must be [valid] for writes.
776 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
779 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
781 /// [valid]: self#safety
789 /// let y = &mut x as *mut i32;
793 /// std::ptr::write(y, z);
794 /// assert_eq!(std::ptr::read(y), 12);
798 /// Manually implement [`mem::swap`]:
803 /// fn swap<T>(a: &mut T, b: &mut T) {
805 /// // Create a bitwise copy of the value at `a` in `tmp`.
806 /// let tmp = ptr::read(a);
808 /// // Exiting at this point (either by explicitly returning or by
809 /// // calling a function which panics) would cause the value in `tmp` to
810 /// // be dropped while the same value is still referenced by `a`. This
811 /// // could trigger undefined behavior if `T` is not `Copy`.
813 /// // Create a bitwise copy of the value at `b` in `a`.
814 /// // This is safe because mutable references cannot alias.
815 /// ptr::copy_nonoverlapping(b, a, 1);
817 /// // As above, exiting here could trigger undefined behavior because
818 /// // the same value is referenced by `a` and `b`.
820 /// // Move `tmp` into `b`.
821 /// ptr::write(b, tmp);
823 /// // `tmp` has been moved (`write` takes ownership of its second argument),
824 /// // so nothing is dropped implicitly here.
828 /// let mut foo = "foo".to_owned();
829 /// let mut bar = "bar".to_owned();
831 /// swap(&mut foo, &mut bar);
833 /// assert_eq!(foo, "bar");
834 /// assert_eq!(bar, "foo");
837 #[stable(feature = "rust1", since = "1.0.0")]
838 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
839 pub const unsafe fn write<T>(dst: *mut T, src: T) {
840 // We are calling the intrinsics directly to avoid function calls in the generated code
841 // as `intrinsics::copy_nonoverlapping` is a wrapper function.
842 extern "rust-intrinsic" {
843 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
844 fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
847 // SAFETY: the caller must guarantee that `dst` is valid for writes.
848 // `dst` cannot overlap `src` because the caller has mutable access
849 // to `dst` while `src` is owned by this function.
851 copy_nonoverlapping(&src as *const T, dst, 1);
852 intrinsics::forget(src);
856 /// Overwrites a memory location with the given value without reading or
857 /// dropping the old value.
859 /// Unlike [`write()`], the pointer may be unaligned.
861 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
862 /// could leak allocations or resources, so care should be taken not to overwrite
863 /// an object that should be dropped.
865 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
866 /// location pointed to by `dst`.
868 /// This is appropriate for initializing uninitialized memory, or overwriting
869 /// memory that has previously been read with [`read_unaligned`].
873 /// Behavior is undefined if any of the following conditions are violated:
875 /// * `dst` must be [valid] for writes.
877 /// Note that even if `T` has size `0`, the pointer must be non-null.
879 /// [valid]: self#safety
881 /// ## On `packed` structs
883 /// Attempting to create a raw pointer to an `unaligned` struct field with
884 /// an expression such as `&packed.unaligned as *const FieldType` creates an
885 /// intermediate unaligned reference before converting that to a raw pointer.
886 /// That this reference is temporary and immediately cast is inconsequential
887 /// as the compiler always expects references to be properly aligned.
888 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
889 /// *undefined behavior* in your program.
891 /// Instead you must use the [`ptr::addr_of_mut!`](addr_of_mut)
892 /// macro to create the pointer. You may use that returned pointer together with
895 /// An example of how to do it and how this relates to `write_unaligned` is:
898 /// #[repr(packed, C)]
904 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
906 /// // Take the address of a 32-bit integer which is not aligned.
907 /// // In contrast to `&packed.unaligned as *mut _`, this has no undefined behavior.
908 /// let unaligned = std::ptr::addr_of_mut!(packed.unaligned);
910 /// unsafe { std::ptr::write_unaligned(unaligned, 42) };
912 /// assert_eq!({packed.unaligned}, 42); // `{...}` forces copying the field instead of creating a reference.
915 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however
916 /// (as can be seen in the `assert_eq!` above).
920 /// Write a usize value to a byte buffer:
925 /// fn write_usize(x: &mut [u8], val: usize) {
926 /// assert!(x.len() >= mem::size_of::<usize>());
928 /// let ptr = x.as_mut_ptr() as *mut usize;
930 /// unsafe { ptr.write_unaligned(val) }
934 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
935 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
936 pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
937 // SAFETY: the caller must guarantee that `dst` is valid for writes.
938 // `dst` cannot overlap `src` because the caller has mutable access
939 // to `dst` while `src` is owned by this function.
941 copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::<T>());
942 // We are calling the intrinsic directly to avoid function calls in the generated code.
943 intrinsics::forget(src);
947 /// Performs a volatile read of the value from `src` without moving it. This
948 /// leaves the memory in `src` unchanged.
950 /// Volatile operations are intended to act on I/O memory, and are guaranteed
951 /// to not be elided or reordered by the compiler across other volatile
956 /// Rust does not currently have a rigorously and formally defined memory model,
957 /// so the precise semantics of what "volatile" means here is subject to change
958 /// over time. That being said, the semantics will almost always end up pretty
959 /// similar to [C11's definition of volatile][c11].
961 /// The compiler shouldn't change the relative order or number of volatile
962 /// memory operations. However, volatile memory operations on zero-sized types
963 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
964 /// and may be ignored.
966 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
970 /// Behavior is undefined if any of the following conditions are violated:
972 /// * `src` must be [valid] for reads.
974 /// * `src` must be properly aligned.
976 /// * `src` must point to a properly initialized value of type `T`.
978 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
979 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
980 /// value and the value at `*src` can [violate memory safety][read-ownership].
981 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
984 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
986 /// [valid]: self#safety
987 /// [read-ownership]: read#ownership-of-the-returned-value
989 /// Just like in C, whether an operation is volatile has no bearing whatsoever
990 /// on questions involving concurrent access from multiple threads. Volatile
991 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
992 /// a race between a `read_volatile` and any write operation to the same location
993 /// is undefined behavior.
1001 /// let y = &x as *const i32;
1004 /// assert_eq!(std::ptr::read_volatile(y), 12);
1008 #[stable(feature = "volatile", since = "1.9.0")]
1009 pub unsafe fn read_volatile<T>(src: *const T) -> T {
1010 if cfg!(debug_assertions) && !is_aligned_and_not_null(src) {
1011 // Not panicking to keep codegen impact smaller.
1014 // SAFETY: the caller must uphold the safety contract for `volatile_load`.
1015 unsafe { intrinsics::volatile_load(src) }
1018 /// Performs a volatile write of a memory location with the given value without
1019 /// reading or dropping the old value.
1021 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1022 /// to not be elided or reordered by the compiler across other volatile
1025 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
1026 /// could leak allocations or resources, so care should be taken not to overwrite
1027 /// an object that should be dropped.
1029 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1030 /// location pointed to by `dst`.
1034 /// Rust does not currently have a rigorously and formally defined memory model,
1035 /// so the precise semantics of what "volatile" means here is subject to change
1036 /// over time. That being said, the semantics will almost always end up pretty
1037 /// similar to [C11's definition of volatile][c11].
1039 /// The compiler shouldn't change the relative order or number of volatile
1040 /// memory operations. However, volatile memory operations on zero-sized types
1041 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
1042 /// and may be ignored.
1044 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1048 /// Behavior is undefined if any of the following conditions are violated:
1050 /// * `dst` must be [valid] for writes.
1052 /// * `dst` must be properly aligned.
1054 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1056 /// [valid]: self#safety
1058 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1059 /// on questions involving concurrent access from multiple threads. Volatile
1060 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1061 /// a race between a `write_volatile` and any other operation (reading or writing)
1062 /// on the same location is undefined behavior.
1070 /// let y = &mut x as *mut i32;
1074 /// std::ptr::write_volatile(y, z);
1075 /// assert_eq!(std::ptr::read_volatile(y), 12);
1079 #[stable(feature = "volatile", since = "1.9.0")]
1080 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
1081 if cfg!(debug_assertions) && !is_aligned_and_not_null(dst) {
1082 // Not panicking to keep codegen impact smaller.
1085 // SAFETY: the caller must uphold the safety contract for `volatile_store`.
1087 intrinsics::volatile_store(dst, src);
1091 /// Align pointer `p`.
1093 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
1094 /// to pointer `p` so that pointer `p` would get aligned to `a`.
1096 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
1097 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
1100 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
1101 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
1102 /// than trying to adapt this to accommodate that change.
1104 /// Any questions go to @nagisa.
1105 #[lang = "align_offset"]
1106 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
1107 // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
1108 // 1, where the method versions of these operations are not inlined.
1110 unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub,
1113 /// Calculate multiplicative modular inverse of `x` modulo `m`.
1115 /// This implementation is tailored for `align_offset` and has following preconditions:
1117 /// * `m` is a power-of-two;
1118 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1120 /// Implementation of this function shall not panic. Ever.
1122 unsafe fn mod_inv(x: usize, m: usize) -> usize {
1123 /// Multiplicative modular inverse table modulo 2⁴ = 16.
1125 /// Note, that this table does not contain values where inverse does not exist (i.e., for
1126 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
1127 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
1128 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
1129 const INV_TABLE_MOD: usize = 16;
1131 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
1133 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
1134 // SAFETY: `m` is required to be a power-of-two, hence non-zero.
1135 let m_minus_one = unsafe { unchecked_sub(m, 1) };
1136 if m <= INV_TABLE_MOD {
1137 table_inverse & m_minus_one
1139 // We iterate "up" using the following formula:
1141 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1143 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
1144 let mut inverse = table_inverse;
1145 let mut going_mod = INV_TABLE_MOD_SQUARED;
1147 // y = y * (2 - xy) mod n
1149 // Note, that we use wrapping operations here intentionally – the original formula
1150 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
1151 // usize::MAX` instead, because we take the result `mod n` at the end
1153 inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse)));
1155 return inverse & m_minus_one;
1157 going_mod = wrapping_mul(going_mod, going_mod);
1162 let stride = mem::size_of::<T>();
1163 // SAFETY: `a` is a power-of-two, therefore non-zero.
1164 let a_minus_one = unsafe { unchecked_sub(a, 1) };
1166 // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so
1167 // inhibits LLVM's ability to select instructions like `lea`. Instead we compute
1169 // round_up_to_next_alignment(p, a) - p
1171 // which distributes operations around the load-bearing, but pessimizing `and` sufficiently
1172 // for LLVM to be able to utilize the various optimizations it knows about.
1173 return wrapping_sub(
1174 wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a),
1179 let pmoda = p as usize & a_minus_one;
1181 // Already aligned. Yay!
1183 } else if stride == 0 {
1184 // If the pointer is not aligned, and the element is zero-sized, then no amount of
1185 // elements will ever align the pointer.
1189 let smoda = stride & a_minus_one;
1190 // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
1191 let gcdpow = unsafe { intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)) };
1192 // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize.
1193 let gcd = unsafe { unchecked_shl(1usize, gcdpow) };
1195 // SAFETY: gcd is always greater or equal to 1.
1196 if p as usize & unsafe { unchecked_sub(gcd, 1) } == 0 {
1197 // This branch solves for the following linear congruence equation:
1199 // ` p + so = 0 mod a `
1201 // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1202 // requested alignment.
1204 // With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
1205 // `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1207 // ` p' + s'o = 0 mod a' `
1208 // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1210 // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the second
1211 // term is "how does incrementing `p` by `s` bytes change the relative alignment of `p`" (again
1213 // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1216 // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1217 // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`.
1219 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1221 let a2 = unsafe { unchecked_shr(a, gcdpow) };
1222 // SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
1223 // in `a` (of which it has exactly one).
1224 let a2minus1 = unsafe { unchecked_sub(a2, 1) };
1225 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1227 let s2 = unsafe { unchecked_shr(smoda, gcdpow) };
1228 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1229 // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
1230 // always be strictly greater than `(p % a) >> gcdpow`.
1231 let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(pmoda, gcdpow)) };
1232 // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
1233 // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
1234 return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;
1237 // Cannot be aligned at all.
1241 /// Compares raw pointers for equality.
1243 /// This is the same as using the `==` operator, but less generic:
1244 /// the arguments have to be `*const T` raw pointers,
1245 /// not anything that implements `PartialEq`.
1247 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
1248 /// by their address rather than comparing the values they point to
1249 /// (which is what the `PartialEq for &T` implementation does).
1257 /// let other_five = 5;
1258 /// let five_ref = &five;
1259 /// let same_five_ref = &five;
1260 /// let other_five_ref = &other_five;
1262 /// assert!(five_ref == same_five_ref);
1263 /// assert!(ptr::eq(five_ref, same_five_ref));
1265 /// assert!(five_ref == other_five_ref);
1266 /// assert!(!ptr::eq(five_ref, other_five_ref));
1269 /// Slices are also compared by their length (fat pointers):
1272 /// let a = [1, 2, 3];
1273 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
1274 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
1275 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
1278 /// Traits are also compared by their implementation:
1281 /// #[repr(transparent)]
1282 /// struct Wrapper { member: i32 }
1285 /// impl Trait for Wrapper {}
1286 /// impl Trait for i32 {}
1288 /// let wrapper = Wrapper { member: 10 };
1290 /// // Pointers have equal addresses.
1291 /// assert!(std::ptr::eq(
1292 /// &wrapper as *const Wrapper as *const u8,
1293 /// &wrapper.member as *const i32 as *const u8
1296 /// // Objects have equal addresses, but `Trait` has different implementations.
1297 /// assert!(!std::ptr::eq(
1298 /// &wrapper as &dyn Trait,
1299 /// &wrapper.member as &dyn Trait,
1301 /// assert!(!std::ptr::eq(
1302 /// &wrapper as &dyn Trait as *const dyn Trait,
1303 /// &wrapper.member as &dyn Trait as *const dyn Trait,
1306 /// // Converting the reference to a `*const u8` compares by address.
1307 /// assert!(std::ptr::eq(
1308 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
1309 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
1312 #[stable(feature = "ptr_eq", since = "1.17.0")]
1314 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
1318 /// Hash a raw pointer.
1320 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
1321 /// by its address rather than the value it points to
1322 /// (which is what the `Hash for &T` implementation does).
1327 /// use std::collections::hash_map::DefaultHasher;
1328 /// use std::hash::{Hash, Hasher};
1332 /// let five_ref = &five;
1334 /// let mut hasher = DefaultHasher::new();
1335 /// ptr::hash(five_ref, &mut hasher);
1336 /// let actual = hasher.finish();
1338 /// let mut hasher = DefaultHasher::new();
1339 /// (five_ref as *const i32).hash(&mut hasher);
1340 /// let expected = hasher.finish();
1342 /// assert_eq!(actual, expected);
1344 #[stable(feature = "ptr_hash", since = "1.35.0")]
1345 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
1346 use crate::hash::Hash;
1350 // Impls for function pointers
1351 macro_rules! fnptr_impls_safety_abi {
1352 ($FnTy: ty, $($Arg: ident),*) => {
1353 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1354 impl<Ret, $($Arg),*> PartialEq for $FnTy {
1356 fn eq(&self, other: &Self) -> bool {
1357 *self as usize == *other as usize
1361 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1362 impl<Ret, $($Arg),*> Eq for $FnTy {}
1364 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1365 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
1367 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1368 (*self as usize).partial_cmp(&(*other as usize))
1372 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1373 impl<Ret, $($Arg),*> Ord for $FnTy {
1375 fn cmp(&self, other: &Self) -> Ordering {
1376 (*self as usize).cmp(&(*other as usize))
1380 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1381 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
1382 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
1383 state.write_usize(*self as usize)
1387 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1388 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
1389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1390 // HACK: The intermediate cast as usize is required for AVR
1391 // so that the address space of the source function pointer
1392 // is preserved in the final function pointer.
1394 // https://github.com/avr-rust/rust/issues/143
1395 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1399 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1400 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
1401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1402 // HACK: The intermediate cast as usize is required for AVR
1403 // so that the address space of the source function pointer
1404 // is preserved in the final function pointer.
1406 // https://github.com/avr-rust/rust/issues/143
1407 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1413 macro_rules! fnptr_impls_args {
1414 ($($Arg: ident),+) => {
1415 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1416 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1417 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1418 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1419 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1420 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1423 // No variadic functions with 0 parameters
1424 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
1425 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
1426 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
1427 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
1431 fnptr_impls_args! {}
1432 fnptr_impls_args! { A }
1433 fnptr_impls_args! { A, B }
1434 fnptr_impls_args! { A, B, C }
1435 fnptr_impls_args! { A, B, C, D }
1436 fnptr_impls_args! { A, B, C, D, E }
1437 fnptr_impls_args! { A, B, C, D, E, F }
1438 fnptr_impls_args! { A, B, C, D, E, F, G }
1439 fnptr_impls_args! { A, B, C, D, E, F, G, H }
1440 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
1441 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
1442 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
1443 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
1445 /// Create a `const` raw pointer to a place, without creating an intermediate reference.
1447 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1448 /// and points to initialized data. For cases where those requirements do not hold,
1449 /// raw pointers should be used instead. However, `&expr as *const _` creates a reference
1450 /// before casting it to a raw pointer, and that reference is subject to the same rules
1451 /// as all other references. This macro can create a raw pointer *without* creating
1452 /// a reference first.
1454 /// Note, however, that the `expr` in `addr_of!(expr)` is still subject to all
1455 /// the usual rules. In particular, `addr_of!(*ptr::null())` is Undefined
1456 /// Behavior because it dereferences a null pointer.
1469 /// let packed = Packed { f1: 1, f2: 2 };
1470 /// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1471 /// let raw_f2 = ptr::addr_of!(packed.f2);
1472 /// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
1475 /// See [`addr_of_mut`] for how to create a pointer to unininitialized data.
1476 /// Doing that with `addr_of` would not make much sense since one could only
1477 /// read the data, and that would be Undefined Behavior.
1478 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1479 #[rustc_macro_transparency = "semitransparent"]
1480 #[allow_internal_unstable(raw_ref_op)]
1481 pub macro addr_of($place:expr) {
1485 /// Create a `mut` raw pointer to a place, without creating an intermediate reference.
1487 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1488 /// and points to initialized data. For cases where those requirements do not hold,
1489 /// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
1490 /// before casting it to a raw pointer, and that reference is subject to the same rules
1491 /// as all other references. This macro can create a raw pointer *without* creating
1492 /// a reference first.
1494 /// Note, however, that the `expr` in `addr_of_mut!(expr)` is still subject to all
1495 /// the usual rules. In particular, `addr_of_mut!(*ptr::null_mut())` is Undefined
1496 /// Behavior because it dereferences a null pointer.
1500 /// **Creating a pointer to unaligned data:**
1511 /// let mut packed = Packed { f1: 1, f2: 2 };
1512 /// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1513 /// let raw_f2 = ptr::addr_of_mut!(packed.f2);
1514 /// unsafe { raw_f2.write_unaligned(42); }
1515 /// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
1518 /// **Creating a pointer to uninitialized data:**
1521 /// use std::{ptr, mem::MaybeUninit};
1527 /// let mut uninit = MaybeUninit::<Demo>::uninit();
1528 /// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
1529 /// // and thus be Undefined Behavior!
1530 /// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
1531 /// unsafe { f1_ptr.write(true); }
1532 /// let init = unsafe { uninit.assume_init() };
1534 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1535 #[rustc_macro_transparency = "semitransparent"]
1536 #[allow_internal_unstable(raw_ref_op)]
1537 pub macro addr_of_mut($place:expr) {