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 //! [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`]: pointer::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}
;
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 = "81513")]
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 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
398 pub const unsafe fn swap
<T
>(x
: *mut T
, y
: *mut T
) {
399 // Give ourselves some scratch space to work with.
400 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
401 let mut tmp
= MaybeUninit
::<T
>::uninit();
404 // SAFETY: the caller must guarantee that `x` and `y` are
405 // valid for writes and properly aligned. `tmp` cannot be
406 // overlapping either `x` or `y` because `tmp` was just allocated
407 // on the stack as a separate allocated object.
409 copy_nonoverlapping(x
, tmp
.as_mut_ptr(), 1);
410 copy(y
, x
, 1); // `x` and `y` may overlap
411 copy_nonoverlapping(tmp
.as_ptr(), y
, 1);
415 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
416 /// beginning at `x` and `y`. The two regions must *not* overlap.
420 /// Behavior is undefined if any of the following conditions are violated:
422 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
423 /// size_of::<T>()` bytes.
425 /// * Both `x` and `y` must be properly aligned.
427 /// * The region of memory beginning at `x` with a size of `count *
428 /// size_of::<T>()` bytes must *not* overlap with the region of memory
429 /// beginning at `y` with the same size.
431 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
432 /// the pointers must be non-NULL and properly aligned.
434 /// [valid]: self#safety
443 /// let mut x = [1, 2, 3, 4];
444 /// let mut y = [7, 8, 9];
447 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
450 /// assert_eq!(x, [7, 8, 3, 4]);
451 /// assert_eq!(y, [1, 2, 9]);
454 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
455 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
456 pub const unsafe fn swap_nonoverlapping
<T
>(x
: *mut T
, y
: *mut T
, count
: usize) {
457 let x
= x
as *mut u8;
458 let y
= y
as *mut u8;
459 let len
= mem
::size_of
::<T
>() * count
;
460 // SAFETY: the caller must guarantee that `x` and `y` are
461 // valid for writes and properly aligned.
462 unsafe { swap_nonoverlapping_bytes(x, y, len) }
466 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
467 pub(crate) const unsafe fn swap_nonoverlapping_one
<T
>(x
: *mut T
, y
: *mut T
) {
468 // For types smaller than the block optimization below,
469 // just swap directly to avoid pessimizing codegen.
470 if mem
::size_of
::<T
>() < 32 {
471 // SAFETY: the caller must guarantee that `x` and `y` are valid
472 // for writes, properly aligned, and non-overlapping.
475 copy_nonoverlapping(y
, x
, 1);
479 // SAFETY: the caller must uphold the safety contract for `swap_nonoverlapping`.
480 unsafe { swap_nonoverlapping(x, y, 1) }
;
485 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
486 const unsafe fn swap_nonoverlapping_bytes(x
: *mut u8, y
: *mut u8, len
: usize) {
487 // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
488 // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
489 // Haswell E processors. LLVM is more able to optimize if we give a struct a
490 // #[repr(simd)], even if we don't actually use this struct directly.
492 // FIXME repr(simd) broken on emscripten and redox
493 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))]
494 struct Block(u64, u64, u64, u64);
495 struct UnalignedBlock(u64, u64, u64, u64);
497 let block_size
= mem
::size_of
::<Block
>();
499 // Loop through x & y, copying them `Block` at a time
500 // The optimizer should unroll the loop fully for most types
501 // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
503 while i
+ block_size
<= len
{
504 // Create some uninitialized memory as scratch space
505 // Declaring `t` here avoids aligning the stack when this loop is unused
506 let mut t
= mem
::MaybeUninit
::<Block
>::uninit();
507 let t
= t
.as_mut_ptr() as *mut u8;
509 // SAFETY: As `i < len`, and as the caller must guarantee that `x` and `y` are valid
510 // for `len` bytes, `x + i` and `y + i` must be valid addresses, which fulfills the
511 // safety contract for `add`.
513 // Also, the caller must guarantee that `x` and `y` are valid for writes, properly aligned,
514 // and non-overlapping, which fulfills the safety contract for `copy_nonoverlapping`.
519 // Swap a block of bytes of x & y, using t as a temporary buffer
520 // This should be optimized into efficient SIMD operations where available
521 copy_nonoverlapping(x
, t
, block_size
);
522 copy_nonoverlapping(y
, x
, block_size
);
523 copy_nonoverlapping(t
, y
, block_size
);
529 // Swap any remaining bytes
530 let mut t
= mem
::MaybeUninit
::<UnalignedBlock
>::uninit();
533 let t
= t
.as_mut_ptr() as *mut u8;
535 // SAFETY: see previous safety comment.
540 copy_nonoverlapping(x
, t
, rem
);
541 copy_nonoverlapping(y
, x
, rem
);
542 copy_nonoverlapping(t
, y
, rem
);
547 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
549 /// Neither value is dropped.
551 /// This function is semantically equivalent to [`mem::replace`] except that it
552 /// operates on raw pointers instead of references. When references are
553 /// available, [`mem::replace`] should be preferred.
557 /// Behavior is undefined if any of the following conditions are violated:
559 /// * `dst` must be [valid] for both reads and writes.
561 /// * `dst` must be properly aligned.
563 /// * `dst` must point to a properly initialized value of type `T`.
565 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
567 /// [valid]: self#safety
574 /// let mut rust = vec!['b', 'u', 's', 't'];
576 /// // `mem::replace` would have the same effect without requiring the unsafe
579 /// ptr::replace(&mut rust[0], 'r')
582 /// assert_eq!(b, 'b');
583 /// assert_eq!(rust, &['r', 'u', 's', 't']);
586 #[stable(feature = "rust1", since = "1.0.0")]
587 #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
588 pub const unsafe fn replace
<T
>(dst
: *mut T
, mut src
: T
) -> T
{
589 // SAFETY: the caller must guarantee that `dst` is valid to be
590 // cast to a mutable reference (valid for writes, aligned, initialized),
591 // and cannot overlap `src` since `dst` must point to a distinct
594 mem
::swap(&mut *dst
, &mut src
); // cannot overlap
599 /// Reads the value from `src` without moving it. This leaves the
600 /// memory in `src` unchanged.
604 /// Behavior is undefined if any of the following conditions are violated:
606 /// * `src` must be [valid] for reads.
608 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
611 /// * `src` must point to a properly initialized value of type `T`.
613 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
621 /// let y = &x as *const i32;
624 /// assert_eq!(std::ptr::read(y), 12);
628 /// Manually implement [`mem::swap`]:
633 /// fn swap<T>(a: &mut T, b: &mut T) {
635 /// // Create a bitwise copy of the value at `a` in `tmp`.
636 /// let tmp = ptr::read(a);
638 /// // Exiting at this point (either by explicitly returning or by
639 /// // calling a function which panics) would cause the value in `tmp` to
640 /// // be dropped while the same value is still referenced by `a`. This
641 /// // could trigger undefined behavior if `T` is not `Copy`.
643 /// // Create a bitwise copy of the value at `b` in `a`.
644 /// // This is safe because mutable references cannot alias.
645 /// ptr::copy_nonoverlapping(b, a, 1);
647 /// // As above, exiting here could trigger undefined behavior because
648 /// // the same value is referenced by `a` and `b`.
650 /// // Move `tmp` into `b`.
651 /// ptr::write(b, tmp);
653 /// // `tmp` has been moved (`write` takes ownership of its second argument),
654 /// // so nothing is dropped implicitly here.
658 /// let mut foo = "foo".to_owned();
659 /// let mut bar = "bar".to_owned();
661 /// swap(&mut foo, &mut bar);
663 /// assert_eq!(foo, "bar");
664 /// assert_eq!(bar, "foo");
667 /// ## Ownership of the Returned Value
669 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
670 /// If `T` is not [`Copy`], using both the returned value and the value at
671 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
672 /// use because it will attempt to drop the value at `*src`.
674 /// [`write()`] can be used to overwrite data without causing it to be dropped.
679 /// let mut s = String::from("foo");
681 /// // `s2` now points to the same underlying memory as `s`.
682 /// let mut s2: String = ptr::read(&s);
684 /// assert_eq!(s2, "foo");
686 /// // Assigning to `s2` causes its original value to be dropped. Beyond
687 /// // this point, `s` must no longer be used, as the underlying memory has
689 /// s2 = String::default();
690 /// assert_eq!(s2, "");
692 /// // Assigning to `s` would cause the old value to be dropped again,
693 /// // resulting in undefined behavior.
694 /// // s = String::from("bar"); // ERROR
696 /// // `ptr::write` can be used to overwrite a value without dropping it.
697 /// ptr::write(&mut s, String::from("bar"));
700 /// assert_eq!(s, "bar");
703 /// [valid]: self#safety
705 #[stable(feature = "rust1", since = "1.0.0")]
706 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
707 pub const unsafe fn read
<T
>(src
: *const T
) -> T
{
708 let mut tmp
= MaybeUninit
::<T
>::uninit();
709 // SAFETY: the caller must guarantee that `src` is valid for reads.
710 // `src` cannot overlap `tmp` because `tmp` was just allocated on
711 // the stack as a separate allocated object.
713 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
714 // to be properly initialized.
716 copy_nonoverlapping(src
, tmp
.as_mut_ptr(), 1);
721 /// Reads the value from `src` without moving it. This leaves the
722 /// memory in `src` unchanged.
724 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
728 /// Behavior is undefined if any of the following conditions are violated:
730 /// * `src` must be [valid] for reads.
732 /// * `src` must point to a properly initialized value of type `T`.
734 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
735 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
736 /// value and the value at `*src` can [violate memory safety][read-ownership].
738 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
740 /// [read-ownership]: read#ownership-of-the-returned-value
741 /// [valid]: self#safety
743 /// ## On `packed` structs
745 /// It is currently impossible to create raw pointers to unaligned fields
746 /// of a packed struct.
748 /// Attempting to create a raw pointer to an `unaligned` struct field with
749 /// an expression such as `&packed.unaligned as *const FieldType` creates an
750 /// intermediate unaligned reference before converting that to a raw pointer.
751 /// That this reference is temporary and immediately cast is inconsequential
752 /// as the compiler always expects references to be properly aligned.
753 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
754 /// *undefined behavior* in your program.
756 /// An example of what not to do and how this relates to `read_unaligned` is:
759 /// #[repr(packed, C)]
765 /// let packed = Packed {
767 /// unaligned: 0x01020304,
771 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
773 /// // A temporary unaligned reference is created here which results in
774 /// // undefined behavior regardless of whether the reference is used or not.
775 /// &packed.unaligned
776 /// // Casting to a raw pointer doesn't help; the mistake already happened.
779 /// let v = std::ptr::read_unaligned(unaligned);
785 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
786 // FIXME: Update docs based on outcome of RFC #2582 and friends.
790 /// Read an usize value from a byte buffer:
795 /// fn read_usize(x: &[u8]) -> usize {
796 /// assert!(x.len() >= mem::size_of::<usize>());
798 /// let ptr = x.as_ptr() as *const usize;
800 /// unsafe { ptr.read_unaligned() }
804 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
805 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
806 pub const unsafe fn read_unaligned
<T
>(src
: *const T
) -> T
{
807 let mut tmp
= MaybeUninit
::<T
>::uninit();
808 // SAFETY: the caller must guarantee that `src` is valid for reads.
809 // `src` cannot overlap `tmp` because `tmp` was just allocated on
810 // the stack as a separate allocated object.
812 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
813 // to be properly initialized.
815 copy_nonoverlapping(src
as *const u8, tmp
.as_mut_ptr() as *mut u8, mem
::size_of
::<T
>());
820 /// Overwrites a memory location with the given value without reading or
821 /// dropping the old value.
823 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
824 /// allocations or resources, so care should be taken not to overwrite an object
825 /// that should be dropped.
827 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
828 /// location pointed to by `dst`.
830 /// This is appropriate for initializing uninitialized memory, or overwriting
831 /// memory that has previously been [`read`] from.
835 /// Behavior is undefined if any of the following conditions are violated:
837 /// * `dst` must be [valid] for writes.
839 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
842 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
844 /// [valid]: self#safety
852 /// let y = &mut x as *mut i32;
856 /// std::ptr::write(y, z);
857 /// assert_eq!(std::ptr::read(y), 12);
861 /// Manually implement [`mem::swap`]:
866 /// fn swap<T>(a: &mut T, b: &mut T) {
868 /// // Create a bitwise copy of the value at `a` in `tmp`.
869 /// let tmp = ptr::read(a);
871 /// // Exiting at this point (either by explicitly returning or by
872 /// // calling a function which panics) would cause the value in `tmp` to
873 /// // be dropped while the same value is still referenced by `a`. This
874 /// // could trigger undefined behavior if `T` is not `Copy`.
876 /// // Create a bitwise copy of the value at `b` in `a`.
877 /// // This is safe because mutable references cannot alias.
878 /// ptr::copy_nonoverlapping(b, a, 1);
880 /// // As above, exiting here could trigger undefined behavior because
881 /// // the same value is referenced by `a` and `b`.
883 /// // Move `tmp` into `b`.
884 /// ptr::write(b, tmp);
886 /// // `tmp` has been moved (`write` takes ownership of its second argument),
887 /// // so nothing is dropped implicitly here.
891 /// let mut foo = "foo".to_owned();
892 /// let mut bar = "bar".to_owned();
894 /// swap(&mut foo, &mut bar);
896 /// assert_eq!(foo, "bar");
897 /// assert_eq!(bar, "foo");
900 #[stable(feature = "rust1", since = "1.0.0")]
901 #[rustc_const_unstable(feature = "const_ptr_write", issue = "none")]
902 pub const unsafe fn write
<T
>(dst
: *mut T
, src
: T
) {
903 // SAFETY: the caller must guarantee that `dst` is valid for writes.
904 // `dst` cannot overlap `src` because the caller has mutable access
905 // to `dst` while `src` is owned by this function.
907 copy_nonoverlapping(&src
as *const T
, dst
, 1);
908 // We are calling the intrinsic directly to avoid function calls in the generated code.
909 intrinsics
::forget(src
);
913 /// Overwrites a memory location with the given value without reading or
914 /// dropping the old value.
916 /// Unlike [`write()`], the pointer may be unaligned.
918 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
919 /// could leak allocations or resources, so care should be taken not to overwrite
920 /// an object that should be dropped.
922 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
923 /// location pointed to by `dst`.
925 /// This is appropriate for initializing uninitialized memory, or overwriting
926 /// memory that has previously been read with [`read_unaligned`].
930 /// Behavior is undefined if any of the following conditions are violated:
932 /// * `dst` must be [valid] for writes.
934 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
936 /// [valid]: self#safety
938 /// ## On `packed` structs
940 /// It is currently impossible to create raw pointers to unaligned fields
941 /// of a packed struct.
943 /// Attempting to create a raw pointer to an `unaligned` struct field with
944 /// an expression such as `&packed.unaligned as *const FieldType` creates an
945 /// intermediate unaligned reference before converting that to a raw pointer.
946 /// That this reference is temporary and immediately cast is inconsequential
947 /// as the compiler always expects references to be properly aligned.
948 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
949 /// *undefined behavior* in your program.
951 /// An example of what not to do and how this relates to `write_unaligned` is:
954 /// #[repr(packed, C)]
960 /// let v = 0x01020304;
961 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
964 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
966 /// // A temporary unaligned reference is created here which results in
967 /// // undefined behavior regardless of whether the reference is used or not.
968 /// &mut packed.unaligned
969 /// // Casting to a raw pointer doesn't help; the mistake already happened.
972 /// std::ptr::write_unaligned(unaligned, v);
978 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
979 // FIXME: Update docs based on outcome of RFC #2582 and friends.
983 /// Write an usize value to a byte buffer:
988 /// fn write_usize(x: &mut [u8], val: usize) {
989 /// assert!(x.len() >= mem::size_of::<usize>());
991 /// let ptr = x.as_mut_ptr() as *mut usize;
993 /// unsafe { ptr.write_unaligned(val) }
997 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
998 #[rustc_const_unstable(feature = "const_ptr_write", issue = "none")]
999 pub const unsafe fn write_unaligned
<T
>(dst
: *mut T
, src
: T
) {
1000 // SAFETY: the caller must guarantee that `dst` is valid for writes.
1001 // `dst` cannot overlap `src` because the caller has mutable access
1002 // to `dst` while `src` is owned by this function.
1004 copy_nonoverlapping(&src
as *const T
as *const u8, dst
as *mut u8, mem
::size_of
::<T
>());
1005 // We are calling the intrinsic directly to avoid function calls in the generated code.
1006 intrinsics
::forget(src
);
1010 /// Performs a volatile read of the value from `src` without moving it. This
1011 /// leaves the memory in `src` unchanged.
1013 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1014 /// to not be elided or reordered by the compiler across other volatile
1019 /// Rust does not currently have a rigorously and formally defined memory model,
1020 /// so the precise semantics of what "volatile" means here is subject to change
1021 /// over time. That being said, the semantics will almost always end up pretty
1022 /// similar to [C11's definition of volatile][c11].
1024 /// The compiler shouldn't change the relative order or number of volatile
1025 /// memory operations. However, volatile memory operations on zero-sized types
1026 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
1027 /// and may be ignored.
1029 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1033 /// Behavior is undefined if any of the following conditions are violated:
1035 /// * `src` must be [valid] for reads.
1037 /// * `src` must be properly aligned.
1039 /// * `src` must point to a properly initialized value of type `T`.
1041 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
1042 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1043 /// value and the value at `*src` can [violate memory safety][read-ownership].
1044 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
1047 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
1049 /// [valid]: self#safety
1050 /// [read-ownership]: read#ownership-of-the-returned-value
1052 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1053 /// on questions involving concurrent access from multiple threads. Volatile
1054 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1055 /// a race between a `read_volatile` and any write operation to the same location
1056 /// is undefined behavior.
1064 /// let y = &x as *const i32;
1067 /// assert_eq!(std::ptr::read_volatile(y), 12);
1071 #[stable(feature = "volatile", since = "1.9.0")]
1072 pub unsafe fn read_volatile
<T
>(src
: *const T
) -> T
{
1073 if cfg
!(debug_assertions
) && !is_aligned_and_not_null(src
) {
1074 // Not panicking to keep codegen impact smaller.
1077 // SAFETY: the caller must uphold the safety contract for `volatile_load`.
1078 unsafe { intrinsics::volatile_load(src) }
1081 /// Performs a volatile write of a memory location with the given value without
1082 /// reading or dropping the old value.
1084 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1085 /// to not be elided or reordered by the compiler across other volatile
1088 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
1089 /// could leak allocations or resources, so care should be taken not to overwrite
1090 /// an object that should be dropped.
1092 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1093 /// location pointed to by `dst`.
1097 /// Rust does not currently have a rigorously and formally defined memory model,
1098 /// so the precise semantics of what "volatile" means here is subject to change
1099 /// over time. That being said, the semantics will almost always end up pretty
1100 /// similar to [C11's definition of volatile][c11].
1102 /// The compiler shouldn't change the relative order or number of volatile
1103 /// memory operations. However, volatile memory operations on zero-sized types
1104 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
1105 /// and may be ignored.
1107 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1111 /// Behavior is undefined if any of the following conditions are violated:
1113 /// * `dst` must be [valid] for writes.
1115 /// * `dst` must be properly aligned.
1117 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
1119 /// [valid]: self#safety
1121 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1122 /// on questions involving concurrent access from multiple threads. Volatile
1123 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1124 /// a race between a `write_volatile` and any other operation (reading or writing)
1125 /// on the same location is undefined behavior.
1133 /// let y = &mut x as *mut i32;
1137 /// std::ptr::write_volatile(y, z);
1138 /// assert_eq!(std::ptr::read_volatile(y), 12);
1142 #[stable(feature = "volatile", since = "1.9.0")]
1143 pub unsafe fn write_volatile
<T
>(dst
: *mut T
, src
: T
) {
1144 if cfg
!(debug_assertions
) && !is_aligned_and_not_null(dst
) {
1145 // Not panicking to keep codegen impact smaller.
1148 // SAFETY: the caller must uphold the safety contract for `volatile_store`.
1150 intrinsics
::volatile_store(dst
, src
);
1154 /// Align pointer `p`.
1156 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
1157 /// to pointer `p` so that pointer `p` would get aligned to `a`.
1159 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
1160 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
1163 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
1164 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
1165 /// than trying to adapt this to accommodate that change.
1167 /// Any questions go to @nagisa.
1168 #[lang = "align_offset"]
1169 pub(crate) unsafe fn align_offset
<T
: Sized
>(p
: *const T
, a
: usize) -> usize {
1170 // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
1171 // 1, where the method versions of these operations are not inlined.
1173 unchecked_shl
, unchecked_shr
, unchecked_sub
, wrapping_add
, wrapping_mul
, wrapping_sub
,
1176 /// Calculate multiplicative modular inverse of `x` modulo `m`.
1178 /// This implementation is tailored for `align_offset` and has following preconditions:
1180 /// * `m` is a power-of-two;
1181 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1183 /// Implementation of this function shall not panic. Ever.
1185 unsafe fn mod_inv(x
: usize, m
: usize) -> usize {
1186 /// Multiplicative modular inverse table modulo 2⁴ = 16.
1188 /// Note, that this table does not contain values where inverse does not exist (i.e., for
1189 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
1190 const INV_TABLE_MOD_16
: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
1191 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
1192 const INV_TABLE_MOD
: usize = 16;
1194 const INV_TABLE_MOD_SQUARED
: usize = INV_TABLE_MOD
* INV_TABLE_MOD
;
1196 let table_inverse
= INV_TABLE_MOD_16
[(x
& (INV_TABLE_MOD
- 1)) >> 1] as usize;
1197 // SAFETY: `m` is required to be a power-of-two, hence non-zero.
1198 let m_minus_one
= unsafe { unchecked_sub(m, 1) }
;
1199 if m
<= INV_TABLE_MOD
{
1200 table_inverse
& m_minus_one
1202 // We iterate "up" using the following formula:
1204 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1206 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
1207 let mut inverse
= table_inverse
;
1208 let mut going_mod
= INV_TABLE_MOD_SQUARED
;
1210 // y = y * (2 - xy) mod n
1212 // Note, that we use wrapping operations here intentionally – the original formula
1213 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
1214 // usize::MAX` instead, because we take the result `mod n` at the end
1216 inverse
= wrapping_mul(inverse
, wrapping_sub(2usize
, wrapping_mul(x
, inverse
)));
1218 return inverse
& m_minus_one
;
1220 going_mod
= wrapping_mul(going_mod
, going_mod
);
1225 let stride
= mem
::size_of
::<T
>();
1226 // SAFETY: `a` is a power-of-two, therefore non-zero.
1227 let a_minus_one
= unsafe { unchecked_sub(a, 1) }
;
1229 // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so
1230 // inhibits LLVM's ability to select instructions like `lea`. Instead we compute
1232 // round_up_to_next_alignment(p, a) - p
1234 // which distributes operations around the load-bearing, but pessimizing `and` sufficiently
1235 // for LLVM to be able to utilize the various optimizations it knows about.
1236 return wrapping_sub(
1237 wrapping_add(p
as usize, a_minus_one
) & wrapping_sub(0, a
),
1242 let pmoda
= p
as usize & a_minus_one
;
1244 // Already aligned. Yay!
1246 } else if stride
== 0 {
1247 // If the pointer is not aligned, and the element is zero-sized, then no amount of
1248 // elements will ever align the pointer.
1252 let smoda
= stride
& a_minus_one
;
1253 // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
1254 let gcdpow
= unsafe { intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)) }
;
1255 // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in an usize.
1256 let gcd
= unsafe { unchecked_shl(1usize, gcdpow) }
;
1258 // SAFETY: gcd is always greater or equal to 1.
1259 if p
as usize & unsafe { unchecked_sub(gcd, 1) }
== 0 {
1260 // This branch solves for the following linear congruence equation:
1262 // ` p + so = 0 mod a `
1264 // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1265 // requested alignment.
1267 // With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
1268 // `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1270 // ` p' + s'o = 0 mod a' `
1271 // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1273 // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the second
1274 // term is "how does incrementing `p` by `s` bytes change the relative alignment of `p`" (again
1276 // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1279 // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1280 // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`.
1282 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1284 let a2
= unsafe { unchecked_shr(a, gcdpow) }
;
1285 // SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
1286 // in `a` (of which it has exactly one).
1287 let a2minus1
= unsafe { unchecked_sub(a2, 1) }
;
1288 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1290 let s2
= unsafe { unchecked_shr(smoda, gcdpow) }
;
1291 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1292 // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
1293 // always be strictly greater than `(p % a) >> gcdpow`.
1294 let minusp2
= unsafe { unchecked_sub(a2, unchecked_shr(pmoda, gcdpow)) }
;
1295 // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
1296 // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
1297 return wrapping_mul(minusp2
, unsafe { mod_inv(s2, a2) }
) & a2minus1
;
1300 // Cannot be aligned at all.
1304 /// Compares raw pointers for equality.
1306 /// This is the same as using the `==` operator, but less generic:
1307 /// the arguments have to be `*const T` raw pointers,
1308 /// not anything that implements `PartialEq`.
1310 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
1311 /// by their address rather than comparing the values they point to
1312 /// (which is what the `PartialEq for &T` implementation does).
1320 /// let other_five = 5;
1321 /// let five_ref = &five;
1322 /// let same_five_ref = &five;
1323 /// let other_five_ref = &other_five;
1325 /// assert!(five_ref == same_five_ref);
1326 /// assert!(ptr::eq(five_ref, same_five_ref));
1328 /// assert!(five_ref == other_five_ref);
1329 /// assert!(!ptr::eq(five_ref, other_five_ref));
1332 /// Slices are also compared by their length (fat pointers):
1335 /// let a = [1, 2, 3];
1336 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
1337 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
1338 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
1341 /// Traits are also compared by their implementation:
1344 /// #[repr(transparent)]
1345 /// struct Wrapper { member: i32 }
1348 /// impl Trait for Wrapper {}
1349 /// impl Trait for i32 {}
1351 /// let wrapper = Wrapper { member: 10 };
1353 /// // Pointers have equal addresses.
1354 /// assert!(std::ptr::eq(
1355 /// &wrapper as *const Wrapper as *const u8,
1356 /// &wrapper.member as *const i32 as *const u8
1359 /// // Objects have equal addresses, but `Trait` has different implementations.
1360 /// assert!(!std::ptr::eq(
1361 /// &wrapper as &dyn Trait,
1362 /// &wrapper.member as &dyn Trait,
1364 /// assert!(!std::ptr::eq(
1365 /// &wrapper as &dyn Trait as *const dyn Trait,
1366 /// &wrapper.member as &dyn Trait as *const dyn Trait,
1369 /// // Converting the reference to a `*const u8` compares by address.
1370 /// assert!(std::ptr::eq(
1371 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
1372 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
1375 #[stable(feature = "ptr_eq", since = "1.17.0")]
1377 pub fn eq
<T
: ?Sized
>(a
: *const T
, b
: *const T
) -> bool
{
1381 /// Hash a raw pointer.
1383 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
1384 /// by its address rather than the value it points to
1385 /// (which is what the `Hash for &T` implementation does).
1390 /// use std::collections::hash_map::DefaultHasher;
1391 /// use std::hash::{Hash, Hasher};
1395 /// let five_ref = &five;
1397 /// let mut hasher = DefaultHasher::new();
1398 /// ptr::hash(five_ref, &mut hasher);
1399 /// let actual = hasher.finish();
1401 /// let mut hasher = DefaultHasher::new();
1402 /// (five_ref as *const i32).hash(&mut hasher);
1403 /// let expected = hasher.finish();
1405 /// assert_eq!(actual, expected);
1407 #[stable(feature = "ptr_hash", since = "1.35.0")]
1408 pub fn hash
<T
: ?Sized
, S
: hash
::Hasher
>(hashee
: *const T
, into
: &mut S
) {
1409 use crate::hash
::Hash
;
1413 // Impls for function pointers
1414 macro_rules
! fnptr_impls_safety_abi
{
1415 ($FnTy
: ty
, $
($Arg
: ident
),*) => {
1416 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1417 impl<Ret
, $
($Arg
),*> PartialEq
for $FnTy
{
1419 fn eq(&self, other
: &Self) -> bool
{
1420 *self as usize == *other
as usize
1424 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1425 impl<Ret
, $
($Arg
),*> Eq
for $FnTy {}
1427 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1428 impl<Ret
, $
($Arg
),*> PartialOrd
for $FnTy
{
1430 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
1431 (*self as usize).partial_cmp(&(*other
as usize))
1435 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1436 impl<Ret
, $
($Arg
),*> Ord
for $FnTy
{
1438 fn cmp(&self, other
: &Self) -> Ordering
{
1439 (*self as usize).cmp(&(*other
as usize))
1443 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1444 impl<Ret
, $
($Arg
),*> hash
::Hash
for $FnTy
{
1445 fn hash
<HH
: hash
::Hasher
>(&self, state
: &mut HH
) {
1446 state
.write_usize(*self as usize)
1450 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1451 impl<Ret
, $
($Arg
),*> fmt
::Pointer
for $FnTy
{
1452 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1453 // HACK: The intermediate cast as usize is required for AVR
1454 // so that the address space of the source function pointer
1455 // is preserved in the final function pointer.
1457 // https://github.com/avr-rust/rust/issues/143
1458 fmt
::Pointer
::fmt(&(*self as usize as *const ()), f
)
1462 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1463 impl<Ret
, $
($Arg
),*> fmt
::Debug
for $FnTy
{
1464 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1465 // HACK: The intermediate cast as usize is required for AVR
1466 // so that the address space of the source function pointer
1467 // is preserved in the final function pointer.
1469 // https://github.com/avr-rust/rust/issues/143
1470 fmt
::Pointer
::fmt(&(*self as usize as *const ()), f
)
1476 macro_rules
! fnptr_impls_args
{
1477 ($
($Arg
: ident
),+) => {
1478 fnptr_impls_safety_abi
! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1479 fnptr_impls_safety_abi
! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1480 fnptr_impls_safety_abi
! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1481 fnptr_impls_safety_abi
! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1482 fnptr_impls_safety_abi
! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1483 fnptr_impls_safety_abi
! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1486 // No variadic functions with 0 parameters
1487 fnptr_impls_safety_abi
! { extern "Rust" fn() -> Ret, }
1488 fnptr_impls_safety_abi
! { extern "C" fn() -> Ret, }
1489 fnptr_impls_safety_abi
! { unsafe extern "Rust" fn() -> Ret, }
1490 fnptr_impls_safety_abi
! { unsafe extern "C" fn() -> Ret, }
1494 fnptr_impls_args
! {}
1495 fnptr_impls_args
! { A }
1496 fnptr_impls_args
! { A, B }
1497 fnptr_impls_args
! { A, B, C }
1498 fnptr_impls_args
! { A, B, C, D }
1499 fnptr_impls_args
! { A, B, C, D, E }
1500 fnptr_impls_args
! { A, B, C, D, E, F }
1501 fnptr_impls_args
! { A, B, C, D, E, F, G }
1502 fnptr_impls_args
! { A, B, C, D, E, F, G, H }
1503 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I }
1504 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I, J }
1505 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I, J, K }
1506 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I, J, K, L }
1508 /// Create a `const` raw pointer to a place, without creating an intermediate reference.
1510 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1511 /// and points to initialized data. For cases where those requirements do not hold,
1512 /// raw pointers should be used instead. However, `&expr as *const _` creates a reference
1513 /// before casting it to a raw pointer, and that reference is subject to the same rules
1514 /// as all other references. This macro can create a raw pointer *without* creating
1515 /// a reference first.
1528 /// let packed = Packed { f1: 1, f2: 2 };
1529 /// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1530 /// let raw_f2 = ptr::addr_of!(packed.f2);
1531 /// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
1533 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1534 #[rustc_macro_transparency = "semitransparent"]
1535 #[allow_internal_unstable(raw_ref_op)]
1536 pub macro addr_of($place
:expr
) {
1540 /// Create a `mut` raw pointer to a place, without creating an intermediate reference.
1542 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1543 /// and points to initialized data. For cases where those requirements do not hold,
1544 /// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
1545 /// before casting it to a raw pointer, and that reference is subject to the same rules
1546 /// as all other references. This macro can create a raw pointer *without* creating
1547 /// a reference first.
1560 /// let mut packed = Packed { f1: 1, f2: 2 };
1561 /// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1562 /// let raw_f2 = ptr::addr_of_mut!(packed.f2);
1563 /// unsafe { raw_f2.write_unaligned(42); }
1564 /// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
1566 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1567 #[rustc_macro_transparency = "semitransparent"]
1568 #[allow_internal_unstable(raw_ref_op)]
1569 pub macro addr_of_mut($place
:expr
) {