1 //! Manually manage memory through raw pointers.
3 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
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 //! [aliasing]: ../../nomicon/aliasing.html
59 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
60 //! [ub]: ../../reference/behavior-considered-undefined.html
61 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
62 //! [atomic operations]: crate::sync::atomic
63 //! [`offset`]: ../../std/primitive.pointer.html#method.offset
65 #![stable(feature = "rust1", since = "1.0.0")]
67 use crate::cmp::Ordering;
70 use crate::intrinsics::{self, abort, is_aligned_and_not_null, is_nonoverlapping};
71 use crate::mem::{self, MaybeUninit};
73 #[stable(feature = "rust1", since = "1.0.0")]
75 pub use crate::intrinsics::copy_nonoverlapping;
77 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use crate::intrinsics::copy;
81 #[stable(feature = "rust1", since = "1.0.0")]
83 pub use crate::intrinsics::write_bytes;
85 #[cfg(not(bootstrap))]
87 #[cfg(not(bootstrap))]
88 pub(crate) use metadata::PtrRepr;
89 #[cfg(not(bootstrap))]
90 #[unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
91 pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin};
94 #[stable(feature = "nonnull", since = "1.25.0")]
95 pub use non_null::NonNull;
98 #[unstable(feature = "ptr_internals", issue = "none")]
99 pub use unique::Unique;
104 /// Executes the destructor (if any) of the pointed-to value.
106 /// This is semantically equivalent to calling [`ptr::read`] and discarding
107 /// the result, but has the following advantages:
109 /// * It is *required* to use `drop_in_place` to drop unsized types like
110 /// trait objects, because they can't be read out onto the stack and
111 /// dropped normally.
113 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
114 /// dropping manually allocated memory (e.g., in the implementations of
115 /// `Box`/`Rc`/`Vec`), as the compiler doesn't need to prove that it's
116 /// sound to elide the copy.
118 /// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
119 /// (pinned data must not be moved before it is dropped).
121 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
122 /// location first using [`ptr::read_unaligned`]. For packed structs, this move is
123 /// done automatically by the compiler. This means the fields of packed structs
124 /// are not dropped in-place.
126 /// [`ptr::read`]: self::read
127 /// [`ptr::read_unaligned`]: self::read_unaligned
128 /// [pinned]: crate::pin
132 /// Behavior is undefined if any of the following conditions are violated:
134 /// * `to_drop` must be [valid] for both reads and writes.
136 /// * `to_drop` must be properly aligned.
138 /// * The value `to_drop` points to must be valid for dropping, which may mean it must uphold
139 /// additional invariants - this is type-dependent.
141 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
142 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
143 /// foo` counts as a use because it will cause the value to be dropped
144 /// again. [`write()`] can be used to overwrite data without causing it to be
147 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
149 /// [valid]: self#safety
153 /// Manually remove the last item from a vector:
159 /// let last = Rc::new(1);
160 /// let weak = Rc::downgrade(&last);
162 /// let mut v = vec![Rc::new(0), last];
165 /// // Get a raw pointer to the last element in `v`.
166 /// let ptr = &mut v[1] as *mut _;
167 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
168 /// // to prevent issues if the `drop_in_place` below panics.
170 /// // Without a call `drop_in_place`, the last item would never be dropped,
171 /// // and the memory it manages would be leaked.
172 /// ptr::drop_in_place(ptr);
175 /// assert_eq!(v, &[0.into()]);
177 /// // Ensure that the last item was dropped.
178 /// assert!(weak.upgrade().is_none());
181 /// Notice that the compiler performs this copy automatically when dropping packed structs,
182 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
184 #[stable(feature = "drop_in_place", since = "1.8.0")]
185 #[lang = "drop_in_place"]
186 #[allow(unconditional_recursion)]
187 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
188 // Code here does not matter - this is replaced by the
189 // real drop glue by the compiler.
191 // SAFETY: see comment above
192 unsafe { drop_in_place(to_drop) }
195 /// Creates a null raw pointer.
202 /// let p: *const i32 = ptr::null();
203 /// assert!(p.is_null());
206 #[stable(feature = "rust1", since = "1.0.0")]
208 #[rustc_const_stable(feature = "const_ptr_null", since = "1.32.0")]
209 pub const fn null<T>() -> *const T {
213 /// Creates a null mutable raw pointer.
220 /// let p: *mut i32 = ptr::null_mut();
221 /// assert!(p.is_null());
224 #[stable(feature = "rust1", since = "1.0.0")]
226 #[rustc_const_stable(feature = "const_ptr_null", since = "1.32.0")]
227 pub const fn null_mut<T>() -> *mut T {
233 pub(crate) union Repr<T> {
234 pub(crate) rust: *const [T],
236 pub(crate) raw: FatPtr<T>,
241 pub(crate) struct FatPtr<T> {
243 pub(crate) len: usize,
247 // Manual impl needed to avoid `T: Clone` bound.
248 impl<T> Clone for FatPtr<T> {
249 fn clone(&self) -> Self {
255 // Manual impl needed to avoid `T: Copy` bound.
256 impl<T> Copy for FatPtr<T> {}
258 /// Forms a raw slice from a pointer and a length.
260 /// The `len` argument is the number of **elements**, not the number of bytes.
262 /// This function is safe, but actually using the return value is unsafe.
263 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
265 /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
272 /// // create a slice pointer when starting out with a pointer to the first element
273 /// let x = [5, 6, 7];
274 /// let raw_pointer = x.as_ptr();
275 /// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
276 /// assert_eq!(unsafe { &*slice }[2], 7);
279 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
280 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
281 pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
284 // SAFETY: Accessing the value from the `Repr` union is safe since *const [T]
285 // and FatPtr have the same memory layouts. Only std can make this
287 unsafe { Repr { raw: FatPtr { data, len } }.rust }
289 #[cfg(not(bootstrap))]
290 from_raw_parts(data.cast(), len)
293 /// Performs the same functionality as [`slice_from_raw_parts`], except that a
294 /// raw mutable slice is returned, as opposed to a raw immutable slice.
296 /// See the documentation of [`slice_from_raw_parts`] for more details.
298 /// This function is safe, but actually using the return value is unsafe.
299 /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
301 /// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
308 /// let x = &mut [5, 6, 7];
309 /// let raw_pointer = x.as_mut_ptr();
310 /// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
313 /// (*slice)[2] = 99; // assign a value at an index in the slice
316 /// assert_eq!(unsafe { &*slice }[2], 99);
319 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
320 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
321 pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
324 // SAFETY: Accessing the value from the `Repr` union is safe since *mut [T]
325 // and FatPtr have the same memory layouts
326 unsafe { Repr { raw: FatPtr { data, len } }.rust_mut }
328 #[cfg(not(bootstrap))]
329 from_raw_parts_mut(data.cast(), len)
332 /// Swaps the values at two mutable locations of the same type, without
333 /// deinitializing either.
335 /// But for the following two exceptions, this function is semantically
336 /// equivalent to [`mem::swap`]:
338 /// * It operates on raw pointers instead of references. When references are
339 /// available, [`mem::swap`] should be preferred.
341 /// * The two pointed-to values may overlap. If the values do overlap, then the
342 /// overlapping region of memory from `x` will be used. This is demonstrated
343 /// in the second example below.
347 /// Behavior is undefined if any of the following conditions are violated:
349 /// * Both `x` and `y` must be [valid] for both reads and writes.
351 /// * Both `x` and `y` must be properly aligned.
353 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
355 /// [valid]: self#safety
359 /// Swapping two non-overlapping regions:
364 /// let mut array = [0, 1, 2, 3];
366 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
367 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
371 /// assert_eq!([2, 3, 0, 1], array);
375 /// Swapping two overlapping regions:
380 /// let mut array = [0, 1, 2, 3];
382 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
383 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
387 /// // The indices `1..3` of the slice overlap between `x` and `y`.
388 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
389 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
390 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
391 /// // This implementation is defined to make the latter choice.
392 /// assert_eq!([1, 0, 1, 2], array);
396 #[stable(feature = "rust1", since = "1.0.0")]
397 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
398 // Give ourselves some scratch space to work with.
399 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
400 let mut tmp = MaybeUninit::<T>::uninit();
403 // SAFETY: the caller must guarantee that `x` and `y` are
404 // valid for writes and properly aligned. `tmp` cannot be
405 // overlapping either `x` or `y` because `tmp` was just allocated
406 // on the stack as a separate allocated object.
408 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
409 copy(y, x, 1); // `x` and `y` may overlap
410 copy_nonoverlapping(tmp.as_ptr(), y, 1);
414 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
415 /// beginning at `x` and `y`. The two regions must *not* overlap.
419 /// Behavior is undefined if any of the following conditions are violated:
421 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
422 /// size_of::<T>()` bytes.
424 /// * Both `x` and `y` must be properly aligned.
426 /// * The region of memory beginning at `x` with a size of `count *
427 /// size_of::<T>()` bytes must *not* overlap with the region of memory
428 /// beginning at `y` with the same size.
430 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
431 /// the pointers must be non-NULL and properly aligned.
433 /// [valid]: self#safety
442 /// let mut x = [1, 2, 3, 4];
443 /// let mut y = [7, 8, 9];
446 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
449 /// assert_eq!(x, [7, 8, 3, 4]);
450 /// assert_eq!(y, [1, 2, 9]);
453 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
454 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
455 if cfg!(debug_assertions)
456 && !(is_aligned_and_not_null(x)
457 && is_aligned_and_not_null(y)
458 && is_nonoverlapping(x, y, count))
460 // Not panicking to keep codegen impact smaller.
464 let x = x as *mut u8;
465 let y = y as *mut u8;
466 let len = mem::size_of::<T>() * count;
467 // SAFETY: the caller must guarantee that `x` and `y` are
468 // valid for writes and properly aligned.
469 unsafe { swap_nonoverlapping_bytes(x, y, len) }
473 pub(crate) unsafe fn swap_nonoverlapping_one<T>(x: *mut T, y: *mut T) {
474 // For types smaller than the block optimization below,
475 // just swap directly to avoid pessimizing codegen.
476 if mem::size_of::<T>() < 32 {
477 // SAFETY: the caller must guarantee that `x` and `y` are valid
478 // for writes, properly aligned, and non-overlapping.
481 copy_nonoverlapping(y, x, 1);
485 // SAFETY: the caller must uphold the safety contract for `swap_nonoverlapping`.
486 unsafe { swap_nonoverlapping(x, y, 1) };
491 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
492 // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
493 // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
494 // Haswell E processors. LLVM is more able to optimize if we give a struct a
495 // #[repr(simd)], even if we don't actually use this struct directly.
497 // FIXME repr(simd) broken on emscripten and redox
498 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))]
499 struct Block(u64, u64, u64, u64);
500 struct UnalignedBlock(u64, u64, u64, u64);
502 let block_size = mem::size_of::<Block>();
504 // Loop through x & y, copying them `Block` at a time
505 // The optimizer should unroll the loop fully for most types
506 // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
508 while i + block_size <= len {
509 // Create some uninitialized memory as scratch space
510 // Declaring `t` here avoids aligning the stack when this loop is unused
511 let mut t = mem::MaybeUninit::<Block>::uninit();
512 let t = t.as_mut_ptr() as *mut u8;
514 // SAFETY: As `i < len`, and as the caller must guarantee that `x` and `y` are valid
515 // for `len` bytes, `x + i` and `y + i` must be valid adresses, which fulfills the
516 // safety contract for `add`.
518 // Also, the caller must guarantee that `x` and `y` are valid for writes, properly aligned,
519 // and non-overlapping, which fulfills the safety contract for `copy_nonoverlapping`.
524 // Swap a block of bytes of x & y, using t as a temporary buffer
525 // This should be optimized into efficient SIMD operations where available
526 copy_nonoverlapping(x, t, block_size);
527 copy_nonoverlapping(y, x, block_size);
528 copy_nonoverlapping(t, y, block_size);
534 // Swap any remaining bytes
535 let mut t = mem::MaybeUninit::<UnalignedBlock>::uninit();
538 let t = t.as_mut_ptr() as *mut u8;
540 // SAFETY: see previous safety comment.
545 copy_nonoverlapping(x, t, rem);
546 copy_nonoverlapping(y, x, rem);
547 copy_nonoverlapping(t, y, rem);
552 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
554 /// Neither value is dropped.
556 /// This function is semantically equivalent to [`mem::replace`] except that it
557 /// operates on raw pointers instead of references. When references are
558 /// available, [`mem::replace`] should be preferred.
562 /// Behavior is undefined if any of the following conditions are violated:
564 /// * `dst` must be [valid] for both reads and writes.
566 /// * `dst` must be properly aligned.
568 /// * `dst` must point to a properly initialized value of type `T`.
570 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
572 /// [valid]: self#safety
579 /// let mut rust = vec!['b', 'u', 's', 't'];
581 /// // `mem::replace` would have the same effect without requiring the unsafe
584 /// ptr::replace(&mut rust[0], 'r')
587 /// assert_eq!(b, 'b');
588 /// assert_eq!(rust, &['r', 'u', 's', 't']);
591 #[stable(feature = "rust1", since = "1.0.0")]
592 pub unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
593 // SAFETY: the caller must guarantee that `dst` is valid to be
594 // cast to a mutable reference (valid for writes, aligned, initialized),
595 // and cannot overlap `src` since `dst` must point to a distinct
598 mem::swap(&mut *dst, &mut src); // cannot overlap
603 /// Reads the value from `src` without moving it. This leaves the
604 /// memory in `src` unchanged.
608 /// Behavior is undefined if any of the following conditions are violated:
610 /// * `src` must be [valid] for reads.
612 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
615 /// * `src` must point to a properly initialized value of type `T`.
617 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
625 /// let y = &x as *const i32;
628 /// assert_eq!(std::ptr::read(y), 12);
632 /// Manually implement [`mem::swap`]:
637 /// fn swap<T>(a: &mut T, b: &mut T) {
639 /// // Create a bitwise copy of the value at `a` in `tmp`.
640 /// let tmp = ptr::read(a);
642 /// // Exiting at this point (either by explicitly returning or by
643 /// // calling a function which panics) would cause the value in `tmp` to
644 /// // be dropped while the same value is still referenced by `a`. This
645 /// // could trigger undefined behavior if `T` is not `Copy`.
647 /// // Create a bitwise copy of the value at `b` in `a`.
648 /// // This is safe because mutable references cannot alias.
649 /// ptr::copy_nonoverlapping(b, a, 1);
651 /// // As above, exiting here could trigger undefined behavior because
652 /// // the same value is referenced by `a` and `b`.
654 /// // Move `tmp` into `b`.
655 /// ptr::write(b, tmp);
657 /// // `tmp` has been moved (`write` takes ownership of its second argument),
658 /// // so nothing is dropped implicitly here.
662 /// let mut foo = "foo".to_owned();
663 /// let mut bar = "bar".to_owned();
665 /// swap(&mut foo, &mut bar);
667 /// assert_eq!(foo, "bar");
668 /// assert_eq!(bar, "foo");
671 /// ## Ownership of the Returned Value
673 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
674 /// If `T` is not [`Copy`], using both the returned value and the value at
675 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
676 /// use because it will attempt to drop the value at `*src`.
678 /// [`write()`] can be used to overwrite data without causing it to be dropped.
683 /// let mut s = String::from("foo");
685 /// // `s2` now points to the same underlying memory as `s`.
686 /// let mut s2: String = ptr::read(&s);
688 /// assert_eq!(s2, "foo");
690 /// // Assigning to `s2` causes its original value to be dropped. Beyond
691 /// // this point, `s` must no longer be used, as the underlying memory has
693 /// s2 = String::default();
694 /// assert_eq!(s2, "");
696 /// // Assigning to `s` would cause the old value to be dropped again,
697 /// // resulting in undefined behavior.
698 /// // s = String::from("bar"); // ERROR
700 /// // `ptr::write` can be used to overwrite a value without dropping it.
701 /// ptr::write(&mut s, String::from("bar"));
704 /// assert_eq!(s, "bar");
707 /// [valid]: self#safety
709 #[stable(feature = "rust1", since = "1.0.0")]
710 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
711 pub const unsafe fn read<T>(src: *const T) -> T {
712 let mut tmp = MaybeUninit::<T>::uninit();
713 // SAFETY: the caller must guarantee that `src` is valid for reads.
714 // `src` cannot overlap `tmp` because `tmp` was just allocated on
715 // the stack as a separate allocated object.
717 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
718 // to be properly initialized.
720 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
725 /// Reads the value from `src` without moving it. This leaves the
726 /// memory in `src` unchanged.
728 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
732 /// Behavior is undefined if any of the following conditions are violated:
734 /// * `src` must be [valid] for reads.
736 /// * `src` must point to a properly initialized value of type `T`.
738 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
739 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
740 /// value and the value at `*src` can [violate memory safety][read-ownership].
742 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
744 /// [read-ownership]: read#ownership-of-the-returned-value
745 /// [valid]: self#safety
747 /// ## On `packed` structs
749 /// It is currently impossible to create raw pointers to unaligned fields
750 /// of a packed struct.
752 /// Attempting to create a raw pointer to an `unaligned` struct field with
753 /// an expression such as `&packed.unaligned as *const FieldType` creates an
754 /// intermediate unaligned reference before converting that to a raw pointer.
755 /// That this reference is temporary and immediately cast is inconsequential
756 /// as the compiler always expects references to be properly aligned.
757 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
758 /// *undefined behavior* in your program.
760 /// An example of what not to do and how this relates to `read_unaligned` is:
763 /// #[repr(packed, C)]
769 /// let packed = Packed {
771 /// unaligned: 0x01020304,
775 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
777 /// // A temporary unaligned reference is created here which results in
778 /// // undefined behavior regardless of whether the reference is used or not.
779 /// &packed.unaligned
780 /// // Casting to a raw pointer doesn't help; the mistake already happened.
783 /// let v = std::ptr::read_unaligned(unaligned);
789 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
790 // FIXME: Update docs based on outcome of RFC #2582 and friends.
794 /// Read an usize value from a byte buffer:
799 /// fn read_usize(x: &[u8]) -> usize {
800 /// assert!(x.len() >= mem::size_of::<usize>());
802 /// let ptr = x.as_ptr() as *const usize;
804 /// unsafe { ptr.read_unaligned() }
808 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
809 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
810 pub const unsafe fn read_unaligned<T>(src: *const T) -> T {
811 let mut tmp = MaybeUninit::<T>::uninit();
812 // SAFETY: the caller must guarantee that `src` is valid for reads.
813 // `src` cannot overlap `tmp` because `tmp` was just allocated on
814 // the stack as a separate allocated object.
816 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
817 // to be properly initialized.
819 copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::<T>());
824 /// Overwrites a memory location with the given value without reading or
825 /// dropping the old value.
827 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
828 /// allocations or resources, so care should be taken not to overwrite an object
829 /// that should be dropped.
831 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
832 /// location pointed to by `dst`.
834 /// This is appropriate for initializing uninitialized memory, or overwriting
835 /// memory that has previously been [`read`] from.
839 /// Behavior is undefined if any of the following conditions are violated:
841 /// * `dst` must be [valid] for writes.
843 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
846 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
848 /// [valid]: self#safety
856 /// let y = &mut x as *mut i32;
860 /// std::ptr::write(y, z);
861 /// assert_eq!(std::ptr::read(y), 12);
865 /// Manually implement [`mem::swap`]:
870 /// fn swap<T>(a: &mut T, b: &mut T) {
872 /// // Create a bitwise copy of the value at `a` in `tmp`.
873 /// let tmp = ptr::read(a);
875 /// // Exiting at this point (either by explicitly returning or by
876 /// // calling a function which panics) would cause the value in `tmp` to
877 /// // be dropped while the same value is still referenced by `a`. This
878 /// // could trigger undefined behavior if `T` is not `Copy`.
880 /// // Create a bitwise copy of the value at `b` in `a`.
881 /// // This is safe because mutable references cannot alias.
882 /// ptr::copy_nonoverlapping(b, a, 1);
884 /// // As above, exiting here could trigger undefined behavior because
885 /// // the same value is referenced by `a` and `b`.
887 /// // Move `tmp` into `b`.
888 /// ptr::write(b, tmp);
890 /// // `tmp` has been moved (`write` takes ownership of its second argument),
891 /// // so nothing is dropped implicitly here.
895 /// let mut foo = "foo".to_owned();
896 /// let mut bar = "bar".to_owned();
898 /// swap(&mut foo, &mut bar);
900 /// assert_eq!(foo, "bar");
901 /// assert_eq!(bar, "foo");
904 #[stable(feature = "rust1", since = "1.0.0")]
905 pub unsafe fn write<T>(dst: *mut T, src: T) {
906 // SAFETY: the caller must guarantee that `dst` is valid for writes.
907 // `dst` cannot overlap `src` because the caller has mutable access
908 // to `dst` while `src` is owned by this function.
910 copy_nonoverlapping(&src as *const T, dst, 1);
911 // We are calling the intrinsic directly to avoid function calls in the generated code.
912 intrinsics::forget(src);
916 /// Overwrites a memory location with the given value without reading or
917 /// dropping the old value.
919 /// Unlike [`write()`], the pointer may be unaligned.
921 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
922 /// could leak allocations or resources, so care should be taken not to overwrite
923 /// an object that should be dropped.
925 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
926 /// location pointed to by `dst`.
928 /// This is appropriate for initializing uninitialized memory, or overwriting
929 /// memory that has previously been read with [`read_unaligned`].
933 /// Behavior is undefined if any of the following conditions are violated:
935 /// * `dst` must be [valid] for writes.
937 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
939 /// [valid]: self#safety
941 /// ## On `packed` structs
943 /// It is currently impossible to create raw pointers to unaligned fields
944 /// of a packed struct.
946 /// Attempting to create a raw pointer to an `unaligned` struct field with
947 /// an expression such as `&packed.unaligned as *const FieldType` creates an
948 /// intermediate unaligned reference before converting that to a raw pointer.
949 /// That this reference is temporary and immediately cast is inconsequential
950 /// as the compiler always expects references to be properly aligned.
951 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
952 /// *undefined behavior* in your program.
954 /// An example of what not to do and how this relates to `write_unaligned` is:
957 /// #[repr(packed, C)]
963 /// let v = 0x01020304;
964 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
967 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
969 /// // A temporary unaligned reference is created here which results in
970 /// // undefined behavior regardless of whether the reference is used or not.
971 /// &mut packed.unaligned
972 /// // Casting to a raw pointer doesn't help; the mistake already happened.
975 /// std::ptr::write_unaligned(unaligned, v);
981 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
982 // FIXME: Update docs based on outcome of RFC #2582 and friends.
986 /// Write an usize value to a byte buffer:
991 /// fn write_usize(x: &mut [u8], val: usize) {
992 /// assert!(x.len() >= mem::size_of::<usize>());
994 /// let ptr = x.as_mut_ptr() as *mut usize;
996 /// unsafe { ptr.write_unaligned(val) }
1000 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
1001 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
1002 // SAFETY: the caller must guarantee that `dst` is valid for writes.
1003 // `dst` cannot overlap `src` because the caller has mutable access
1004 // to `dst` while `src` is owned by this function.
1006 copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::<T>());
1011 /// Performs a volatile read of the value from `src` without moving it. This
1012 /// leaves the memory in `src` unchanged.
1014 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1015 /// to not be elided or reordered by the compiler across other volatile
1020 /// Rust does not currently have a rigorously and formally defined memory model,
1021 /// so the precise semantics of what "volatile" means here is subject to change
1022 /// over time. That being said, the semantics will almost always end up pretty
1023 /// similar to [C11's definition of volatile][c11].
1025 /// The compiler shouldn't change the relative order or number of volatile
1026 /// memory operations. However, volatile memory operations on zero-sized types
1027 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
1028 /// and may be ignored.
1030 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1034 /// Behavior is undefined if any of the following conditions are violated:
1036 /// * `src` must be [valid] for reads.
1038 /// * `src` must be properly aligned.
1040 /// * `src` must point to a properly initialized value of type `T`.
1042 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
1043 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1044 /// value and the value at `*src` can [violate memory safety][read-ownership].
1045 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
1048 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
1050 /// [valid]: self#safety
1051 /// [read-ownership]: read#ownership-of-the-returned-value
1053 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1054 /// on questions involving concurrent access from multiple threads. Volatile
1055 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1056 /// a race between a `read_volatile` and any write operation to the same location
1057 /// is undefined behavior.
1065 /// let y = &x as *const i32;
1068 /// assert_eq!(std::ptr::read_volatile(y), 12);
1072 #[stable(feature = "volatile", since = "1.9.0")]
1073 pub unsafe fn read_volatile<T>(src: *const T) -> T {
1074 if cfg!(debug_assertions) && !is_aligned_and_not_null(src) {
1075 // Not panicking to keep codegen impact smaller.
1078 // SAFETY: the caller must uphold the safety contract for `volatile_load`.
1079 unsafe { intrinsics::volatile_load(src) }
1082 /// Performs a volatile write of a memory location with the given value without
1083 /// reading or dropping the old value.
1085 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1086 /// to not be elided or reordered by the compiler across other volatile
1089 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
1090 /// could leak allocations or resources, so care should be taken not to overwrite
1091 /// an object that should be dropped.
1093 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1094 /// location pointed to by `dst`.
1098 /// Rust does not currently have a rigorously and formally defined memory model,
1099 /// so the precise semantics of what "volatile" means here is subject to change
1100 /// over time. That being said, the semantics will almost always end up pretty
1101 /// similar to [C11's definition of volatile][c11].
1103 /// The compiler shouldn't change the relative order or number of volatile
1104 /// memory operations. However, volatile memory operations on zero-sized types
1105 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
1106 /// and may be ignored.
1108 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1112 /// Behavior is undefined if any of the following conditions are violated:
1114 /// * `dst` must be [valid] for writes.
1116 /// * `dst` must be properly aligned.
1118 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
1120 /// [valid]: self#safety
1122 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1123 /// on questions involving concurrent access from multiple threads. Volatile
1124 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1125 /// a race between a `write_volatile` and any other operation (reading or writing)
1126 /// on the same location is undefined behavior.
1134 /// let y = &mut x as *mut i32;
1138 /// std::ptr::write_volatile(y, z);
1139 /// assert_eq!(std::ptr::read_volatile(y), 12);
1143 #[stable(feature = "volatile", since = "1.9.0")]
1144 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
1145 if cfg!(debug_assertions) && !is_aligned_and_not_null(dst) {
1146 // Not panicking to keep codegen impact smaller.
1149 // SAFETY: the caller must uphold the safety contract for `volatile_store`.
1151 intrinsics::volatile_store(dst, src);
1155 /// Align pointer `p`.
1157 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
1158 /// to pointer `p` so that pointer `p` would get aligned to `a`.
1160 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
1161 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
1164 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
1165 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
1166 /// than trying to adapt this to accommodate that change.
1168 /// Any questions go to @nagisa.
1169 #[lang = "align_offset"]
1170 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
1171 // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
1172 // 1, where the method versions of these operations are not inlined.
1174 unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub,
1177 /// Calculate multiplicative modular inverse of `x` modulo `m`.
1179 /// This implementation is tailored for `align_offset` and has following preconditions:
1181 /// * `m` is a power-of-two;
1182 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1184 /// Implementation of this function shall not panic. Ever.
1186 unsafe fn mod_inv(x: usize, m: usize) -> usize {
1187 /// Multiplicative modular inverse table modulo 2⁴ = 16.
1189 /// Note, that this table does not contain values where inverse does not exist (i.e., for
1190 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
1191 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
1192 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
1193 const INV_TABLE_MOD: usize = 16;
1195 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
1197 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
1198 // SAFETY: `m` is required to be a power-of-two, hence non-zero.
1199 let m_minus_one = unsafe { unchecked_sub(m, 1) };
1200 if m <= INV_TABLE_MOD {
1201 table_inverse & m_minus_one
1203 // We iterate "up" using the following formula:
1205 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1207 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
1208 let mut inverse = table_inverse;
1209 let mut going_mod = INV_TABLE_MOD_SQUARED;
1211 // y = y * (2 - xy) mod n
1213 // Note, that we use wrapping operations here intentionally – the original formula
1214 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
1215 // usize::MAX` instead, because we take the result `mod n` at the end
1217 inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse)));
1219 return inverse & m_minus_one;
1221 going_mod = wrapping_mul(going_mod, going_mod);
1226 let stride = mem::size_of::<T>();
1227 // SAFETY: `a` is a power-of-two, therefore non-zero.
1228 let a_minus_one = unsafe { unchecked_sub(a, 1) };
1230 // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so
1231 // inhibits LLVM's ability to select instructions like `lea`. Instead we compute
1233 // round_up_to_next_alignment(p, a) - p
1235 // which distributes operations around the load-bearing, but pessimizing `and` sufficiently
1236 // for LLVM to be able to utilize the various optimizations it knows about.
1237 return wrapping_sub(
1238 wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a),
1243 let pmoda = p as usize & a_minus_one;
1245 // Already aligned. Yay!
1247 } else if stride == 0 {
1248 // If the pointer is not aligned, and the element is zero-sized, then no amount of
1249 // elements will ever align the pointer.
1253 let smoda = stride & a_minus_one;
1254 // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
1255 let gcdpow = unsafe { intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)) };
1256 // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in an usize.
1257 let gcd = unsafe { unchecked_shl(1usize, gcdpow) };
1259 // SAFETY: gcd is always greater or equal to 1.
1260 if p as usize & unsafe { unchecked_sub(gcd, 1) } == 0 {
1261 // This branch solves for the following linear congruence equation:
1263 // ` p + so = 0 mod a `
1265 // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1266 // requested alignment.
1268 // With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
1269 // `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1271 // ` p' + s'o = 0 mod a' `
1272 // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1274 // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the second
1275 // term is "how does incrementing `p` by `s` bytes change the relative alignment of `p`" (again
1277 // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1280 // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1281 // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`.
1283 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1285 let a2 = unsafe { unchecked_shr(a, gcdpow) };
1286 // SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
1287 // in `a` (of which it has exactly one).
1288 let a2minus1 = unsafe { unchecked_sub(a2, 1) };
1289 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1291 let s2 = unsafe { unchecked_shr(smoda, gcdpow) };
1292 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1293 // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
1294 // always be strictly greater than `(p % a) >> gcdpow`.
1295 let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(pmoda, gcdpow)) };
1296 // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
1297 // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
1298 return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;
1301 // Cannot be aligned at all.
1305 /// Compares raw pointers for equality.
1307 /// This is the same as using the `==` operator, but less generic:
1308 /// the arguments have to be `*const T` raw pointers,
1309 /// not anything that implements `PartialEq`.
1311 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
1312 /// by their address rather than comparing the values they point to
1313 /// (which is what the `PartialEq for &T` implementation does).
1321 /// let other_five = 5;
1322 /// let five_ref = &five;
1323 /// let same_five_ref = &five;
1324 /// let other_five_ref = &other_five;
1326 /// assert!(five_ref == same_five_ref);
1327 /// assert!(ptr::eq(five_ref, same_five_ref));
1329 /// assert!(five_ref == other_five_ref);
1330 /// assert!(!ptr::eq(five_ref, other_five_ref));
1333 /// Slices are also compared by their length (fat pointers):
1336 /// let a = [1, 2, 3];
1337 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
1338 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
1339 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
1342 /// Traits are also compared by their implementation:
1345 /// #[repr(transparent)]
1346 /// struct Wrapper { member: i32 }
1349 /// impl Trait for Wrapper {}
1350 /// impl Trait for i32 {}
1352 /// let wrapper = Wrapper { member: 10 };
1354 /// // Pointers have equal addresses.
1355 /// assert!(std::ptr::eq(
1356 /// &wrapper as *const Wrapper as *const u8,
1357 /// &wrapper.member as *const i32 as *const u8
1360 /// // Objects have equal addresses, but `Trait` has different implementations.
1361 /// assert!(!std::ptr::eq(
1362 /// &wrapper as &dyn Trait,
1363 /// &wrapper.member as &dyn Trait,
1365 /// assert!(!std::ptr::eq(
1366 /// &wrapper as &dyn Trait as *const dyn Trait,
1367 /// &wrapper.member as &dyn Trait as *const dyn Trait,
1370 /// // Converting the reference to a `*const u8` compares by address.
1371 /// assert!(std::ptr::eq(
1372 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
1373 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
1376 #[stable(feature = "ptr_eq", since = "1.17.0")]
1378 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
1382 /// Hash a raw pointer.
1384 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
1385 /// by its address rather than the value it points to
1386 /// (which is what the `Hash for &T` implementation does).
1391 /// use std::collections::hash_map::DefaultHasher;
1392 /// use std::hash::{Hash, Hasher};
1396 /// let five_ref = &five;
1398 /// let mut hasher = DefaultHasher::new();
1399 /// ptr::hash(five_ref, &mut hasher);
1400 /// let actual = hasher.finish();
1402 /// let mut hasher = DefaultHasher::new();
1403 /// (five_ref as *const i32).hash(&mut hasher);
1404 /// let expected = hasher.finish();
1406 /// assert_eq!(actual, expected);
1408 #[stable(feature = "ptr_hash", since = "1.35.0")]
1409 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
1410 use crate::hash::Hash;
1414 // Impls for function pointers
1415 macro_rules! fnptr_impls_safety_abi {
1416 ($FnTy: ty, $($Arg: ident),*) => {
1417 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1418 impl<Ret, $($Arg),*> PartialEq for $FnTy {
1420 fn eq(&self, other: &Self) -> bool {
1421 *self as usize == *other as usize
1425 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1426 impl<Ret, $($Arg),*> Eq for $FnTy {}
1428 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1429 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
1431 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1432 (*self as usize).partial_cmp(&(*other as usize))
1436 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1437 impl<Ret, $($Arg),*> Ord for $FnTy {
1439 fn cmp(&self, other: &Self) -> Ordering {
1440 (*self as usize).cmp(&(*other as usize))
1444 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1445 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
1446 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
1447 state.write_usize(*self as usize)
1451 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1452 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
1453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1454 // HACK: The intermediate cast as usize is required for AVR
1455 // so that the address space of the source function pointer
1456 // is preserved in the final function pointer.
1458 // https://github.com/avr-rust/rust/issues/143
1459 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1463 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1464 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
1465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1466 // HACK: The intermediate cast as usize is required for AVR
1467 // so that the address space of the source function pointer
1468 // is preserved in the final function pointer.
1470 // https://github.com/avr-rust/rust/issues/143
1471 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1477 macro_rules! fnptr_impls_args {
1478 ($($Arg: ident),+) => {
1479 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1480 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1481 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1482 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1483 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1484 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1487 // No variadic functions with 0 parameters
1488 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
1489 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
1490 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
1491 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
1495 fnptr_impls_args! {}
1496 fnptr_impls_args! { A }
1497 fnptr_impls_args! { A, B }
1498 fnptr_impls_args! { A, B, C }
1499 fnptr_impls_args! { A, B, C, D }
1500 fnptr_impls_args! { A, B, C, D, E }
1501 fnptr_impls_args! { A, B, C, D, E, F }
1502 fnptr_impls_args! { A, B, C, D, E, F, G }
1503 fnptr_impls_args! { A, B, C, D, E, F, G, H }
1504 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
1505 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
1506 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
1507 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
1509 /// Create a `const` raw pointer to a place, without creating an intermediate reference.
1511 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1512 /// and points to initialized data. For cases where those requirements do not hold,
1513 /// raw pointers should be used instead. However, `&expr as *const _` creates a reference
1514 /// before casting it to a raw pointer, and that reference is subject to the same rules
1515 /// as all other references. This macro can create a raw pointer *without* creating
1516 /// a reference first.
1529 /// let packed = Packed { f1: 1, f2: 2 };
1530 /// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1531 /// let raw_f2 = ptr::addr_of!(packed.f2);
1532 /// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
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($place:expr) {
1541 /// Create a `mut` raw pointer to a place, without creating an intermediate reference.
1543 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1544 /// and points to initialized data. For cases where those requirements do not hold,
1545 /// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
1546 /// before casting it to a raw pointer, and that reference is subject to the same rules
1547 /// as all other references. This macro can create a raw pointer *without* creating
1548 /// a reference first.
1561 /// let mut packed = Packed { f1: 1, f2: 2 };
1562 /// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1563 /// let raw_f2 = ptr::addr_of_mut!(packed.f2);
1564 /// unsafe { raw_f2.write_unaligned(42); }
1565 /// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
1567 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1568 #[rustc_macro_transparency = "semitransparent"]
1569 #[allow_internal_unstable(raw_ref_op)]
1570 pub macro addr_of_mut($place:expr) {