1 //! Manually manage memory through raw pointers.
3 //! *[See also the pointer primitive types](pointer).*
7 //! Many functions in this module take raw pointers as arguments and read from
8 //! or write to them. For this to be safe, these pointers must be *valid*.
9 //! Whether a pointer is valid depends on the operation it is used for
10 //! (read or write), and the extent of the memory that is accessed (i.e.,
11 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
12 //! to access only a single value, in which case the documentation omits the size
13 //! and implicitly assumes it to be `size_of::<T>()` bytes.
15 //! The precise rules for validity are not determined yet. The guarantees that are
16 //! provided at this point are very minimal:
18 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
19 //! * For a pointer to be valid, it is necessary, but not always sufficient, that the pointer
20 //! be *dereferenceable*: the memory range of the given size starting at the pointer must all be
21 //! within the bounds of a single allocated object. Note that in Rust,
22 //! every (stack-allocated) variable is considered a separate allocated object.
23 //! * Even for operations of [size zero][zst], the pointer must not be pointing to deallocated
24 //! memory, i.e., deallocation makes pointers invalid even for zero-sized operations. However,
25 //! casting any non-zero integer *literal* to a pointer is valid for zero-sized accesses, even if
26 //! some memory happens to exist at that address and gets deallocated. This corresponds to writing
27 //! your own allocator: allocating zero-sized objects is not very hard. The canonical way to
28 //! obtain a pointer that is valid for zero-sized accesses is [`NonNull::dangling`].
29 //! * All accesses performed by functions in this module are *non-atomic* in the sense
30 //! of [atomic operations] used to synchronize between threads. This means it is
31 //! undefined behavior to perform two concurrent accesses to the same location from different
32 //! threads unless both accesses only read from memory. Notice that this explicitly
33 //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
34 //! be used for inter-thread synchronization.
35 //! * The result of casting a reference to a pointer is valid for as long as the
36 //! underlying object is live and no reference (just raw pointers) is used to
37 //! access the same memory.
39 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
40 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
41 //! will be provided eventually, as the [aliasing] rules are being determined. For more
42 //! information, see the [book] as well as the section in the reference devoted
43 //! to [undefined behavior][ub].
47 //! Valid raw pointers as defined above are not necessarily properly aligned (where
48 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
49 //! aligned to `mem::align_of::<T>()`). However, most functions require their
50 //! arguments to be properly aligned, and will explicitly state
51 //! this requirement in their documentation. Notable exceptions to this are
52 //! [`read_unaligned`] and [`write_unaligned`].
54 //! When a function requires proper alignment, it does so even if the access
55 //! has size 0, i.e., even if memory is not actually touched. Consider using
56 //! [`NonNull::dangling`] in such cases.
58 //! ## Allocated object
60 //! For several operations, such as [`offset`] or field projections (`expr.field`), the notion of an
61 //! "allocated object" becomes relevant. An allocated object is a contiguous region of memory.
62 //! Common examples of allocated objects include stack-allocated variables (each variable is a
63 //! separate allocated object), heap allocations (each allocation created by the global allocator is
64 //! a separate allocated object), and `static` variables.
67 //! # Strict Provenance
69 //! **The following text is non-normative, insufficiently formal, and is an extremely strict
70 //! interpretation of provenance. It's ok if your code doesn't strictly conform to it.**
72 //! [Strict Provenance][] is an experimental set of APIs that help tools that try
73 //! to validate the memory-safety of your program's execution. Notably this includes [miri][]
74 //! and [CHERI][], which can detect when you access out of bounds memory or otherwise violate
75 //! Rust's memory model.
77 //! Provenance must exist in some form for any programming
78 //! language compiled for modern computer architectures, but specifying a model for provenance
79 //! in a way that is useful to both compilers and programmers is an ongoing challenge.
80 //! The [Strict Provenance][] experiment seeks to explore the question: *what if we just said you
81 //! couldn't do all the nasty operations that make provenance so messy?*
83 //! What APIs would have to be removed? What APIs would have to be added? How much would code
84 //! have to change, and is it worse or better now? Would any patterns become truly inexpressible?
85 //! Could we carve out special exceptions for those patterns? Should we?
87 //! A secondary goal of this project is to see if we can disamiguate the many functions of
88 //! pointer<->integer casts enough for the definition of `usize` to be loosened so that it
89 //! isn't *pointer*-sized but address-space/offset/allocation-sized (we'll probably continue
90 //! to conflate these notions). This would potentially make it possible to more efficiently
91 //! target platforms where pointers are larger than offsets, such as CHERI and maybe some
92 //! segmented architecures.
96 //! **This section is *non-normative* and is part of the [Strict Provenance][] experiment.**
98 //! Pointers are not *simply* an "integer" or "address". For instance, it's uncontroversial
99 //! to say that a Use After Free is clearly Undefined Behaviour, even if you "get lucky"
100 //! and the freed memory gets reallocated before your read/write (in fact this is the
101 //! worst-case scenario, UAFs would be much less concerning if this didn't happen!).
102 //! To rationalize this claim, pointers need to somehow be *more* than just their addresses:
103 //! they must have provenance.
105 //! When an allocation is created, that allocation has a unique Original Pointer. For alloc
106 //! APIs this is literally the pointer the call returns, and for variables declarations this
107 //! is the name of the variable. This is mildly overloading the term "pointer" for the sake
108 //! of brevity/exposition.
110 //! The Original Pointer for an allocation is guaranteed to have unique access to the entire
111 //! allocation and *only* that allocation. In this sense, an allocation can be thought of
112 //! as a "sandbox" that cannot be broken into or out of. *Provenance* is the permission
113 //! to access an allocation's sandbox and has both a *spatial* and *temporal* component:
115 //! * Spatial: A range of bytes in the allocation that the pointer is allowed to access.
116 //! * Temporal: Some kind of globally unique identifier tied to the allocation itself.
118 //! Spatial provenance makes sure you don't go beyond your sandbox, while temporal provenance
119 //! makes sure that you can't "get lucky" after your permission to access some memory
120 //! has been revoked (either through deallocations or borrows expiring).
122 //! Provenance is implicitly shared with all pointers transitively derived from
123 //! The Original Pointer through operations like [`offset`], borrowing, and pointer casts.
124 //! Some operations may *shrink* the derived provenance, limiting how much memory it can
125 //! access or how long it's valid for (i.e. borrowing a subfield and subslicing).
127 //! Shrinking provenance cannot be undone: even if you "know" there is a larger allocation, you
128 //! can't derive a pointer with a larger provenance. Similarly, you cannot "recombine"
129 //! two contiguous provenances back into one (i.e. with a `fn merge(&[T], &[T]) -> &[T]`).
131 //! A reference to a value always has provenance over exactly the memory that field occupies.
132 //! A reference to a slice always has provenance over exactly the range that slice describes.
134 //! If an allocation is deallocated, all pointers with provenance to that allocation become
135 //! invalidated, and effectively lose their provenance.
137 //! The strict provenance experiment is mostly only interested in exploring stricter *spatial*
138 //! provenance. In this sense it can be thought of as a subset of the more ambitious and
139 //! formal [Stacked Borrows][] research project, which is what tools like [miri][] are based on.
140 //! In particular, Stacked Borrows is necessary to properly describe what borrows are allowed
141 //! to do and when they become invalidated. This necessarily involves much more complex
142 //! *temporal* reasoning than simply identifying allocations.
145 //! ## Pointer Vs Addresses
147 //! **This section is *non-normative* and is part of the [Strict Provenance][] experiment.**
149 //! One of the largest historical issues with trying to define provenance is that programmers
150 //! freely convert between pointers and integers. Once you allow for this, it generally becomes
151 //! impossible to accurately track and preserve provenance information, and you need to appeal
152 //! to very complex and unreliable heuristics. But of course, converting between pointers and
153 //! integers is very useful, so what can we do?
155 //! Strict Provenance attempts to square this circle by decoupling Rust's traditional conflation
156 //! of pointers and `usize` (and `isize`), defining a pointer to semantically contain the following
159 //! * The **address-space** it is part of.
160 //! * The **address** it points to, which can be represented by a `usize`.
161 //! * The **provenance** it has, defining the memory it has permission to access.
163 //! Under Strict Provenance, a usize *cannot* accurately represent a pointer, and converting from
164 //! a pointer to a usize is generally an operation which *only* extracts the address. It is
165 //! therefore *impossible* to construct a valid pointer from a usize because there is no way
166 //! to restore the address-space and provenance.
168 //! The key insight to making this model *at all* viable is the [`with_addr`][] method:
171 //! /// Creates a new pointer with the given address.
173 //! /// This performs the same operation as an `addr as ptr` cast, but copies
174 //! /// the *address-space* and *provenance* of `self` to the new pointer.
175 //! /// This allows us to dynamically preserve and propagate this important
176 //! /// information in a way that is otherwise impossible with a unary cast.
178 //! /// This is equivalent to using `wrapping_offset` to offset `self` to the
179 //! /// given address, and therefore has all the same capabilities and restrictions.
180 //! pub fn with_addr(self, addr: usize) -> Self;
183 //! So you're still able to drop down to the address representation and do whatever
184 //! clever bit tricks you want *as long as* you're able to keep around a pointer
185 //! into the allocation you care about that can "reconstitute" the other parts of the pointer.
186 //! Usually this is very easy, because you only are taking a pointer, messing with the address,
187 //! and then immediately converting back to a pointer. To make this use case more ergonomic,
188 //! we provide the [`map_addr`][] method.
190 //! To help make it clear that code is "following" Strict Provenance semantics, we also
191 //! provide an [`addr`][] method which is currently equivalent to `ptr as usize`. In the
192 //! future we may provide a lint for pointer<->integer casts to help you audit if your
193 //! code conforms to strict provenance.
196 //! ## Using Strict Provenance
198 //! Most code needs no changes to conform to strict provenance, as the only really concerning
199 //! operation that *wasn't* obviously already Undefined Behaviour is casts from usize to a
200 //! pointer. For code which *does* cast a usize to a pointer, the scope of the change depends
201 //! on exactly what you're doing.
203 //! In general you just need to make sure that if you want to convert a usize address to a
204 //! pointer and then use that pointer to read/write memory, you need to keep around a pointer
205 //! that has sufficient provenance to perform that read/write itself. In this way all of your
206 //! casts from an address to a pointer are essentially just applying offsets/indexing.
208 //! This is generally trivial to do for simple cases like tagged pointers *as long as you
209 //! represent the tagged pointer as an actual pointer and not a usize*. For instance:
212 //! #![feature(strict_provenance)]
215 //! // A flag we want to pack into our pointer
216 //! static HAS_DATA: usize = 0x1;
217 //! static FLAG_MASK: usize = !HAS_DATA;
219 //! // Our value, which must have enough alignment to have spare least-significant-bits.
220 //! let my_precious_data: u32 = 17;
221 //! assert!(core::mem::align_of::<u32>() > 1);
223 //! // Create a tagged pointer
224 //! let ptr = &my_precious_data as *const u32;
225 //! let tagged = ptr.map_addr(|addr| addr | HAS_DATA);
227 //! // Check the flag:
228 //! if tagged.addr() & HAS_DATA != 0 {
229 //! // Untag and read the pointer
230 //! let data = *tagged.map_addr(|addr| addr & FLAG_MASK);
231 //! assert_eq!(data, 17);
238 //! Something more complicated and just generally *evil* like a XOR-List requires more significant
239 //! changes like allocating all nodes in a pre-allocated Vec or Arena and using a pointer
240 //! to the whole allocation to reconstitute the XORed addresses.
242 //! Situations where a valid pointer *must* be created from just an address, such as baremetal code
243 //! accessing a memory-mapped interface at a fixed address, are an open question on how to support.
244 //! These situations *will* still be allowed, but we might require some kind of "I know what I'm
245 //! doing" annotation to explain the situation to the compiler. Because those situations require
246 //! `volatile` accesses anyway, it should be possible to carve out exceptions for them.
248 //! Under [Strict Provenance] is is Undefined Behaviour to:
250 //! * Access memory through a pointer that does not have provenance over that memory.
252 //! * [`offset`] a pointer to an address it doesn't have provenance over.
253 //! This means it's always UB to offset a pointer derived from something deallocated,
254 //! even if the offset is 0. Note that a pointer "one past the end" of its provenance
255 //! is not actually outside its provenance, it just has 0 bytes it can load/store.
257 //! But it *is* still sound to:
259 //! * Create an invalid pointer from just an address (see [`ptr::invalid`][]). This can
260 //! be used for sentinel values like `null` *or* to represent a tagged pointer that will
261 //! never be dereferencable.
263 //! * Forge an allocation of size zero at any sufficiently aligned non-null address.
264 //! i.e. the usual "ZSTs are fake, do what you want" rules apply *but* this only applies
265 //! for actual forgery (integers cast to pointers). If you borrow some structs subfield
266 //! that *happens* to be zero-sized, the resulting pointer will have provenance tied to
267 //! that allocation and it will still get invalidated if the allocation gets deallocated.
268 //! In the future we may introduce an API to make such a forged allocation explicit.
270 //! * [`wrapping_offset`][] a pointer outside its provenance. This includes invalid pointers
271 //! which have "no" provenance. Unfortunately there may be practical limits on this for a
272 //! particular platform, and it's an open question as to how to specify this (if at all).
273 //! Notably, [CHERI][] relies on a compression scheme that can't handle a
274 //! pointer getting offset "too far" out of bounds. If this happens, the address
275 //! returned by `addr` will be the value you expect, but the provenance will get invalidated
276 //! and using it to read/write will fault. The details of this are architecture-specific
277 //! and based on alignment, but the buffer on either side of the pointer's range is pretty
278 //! generous (think kilobytes, not bytes).
280 //! * Perform pointer tagging tricks. This falls out of [`wrapping_offset`] but is worth
281 //! mentioning in more detail because of the limitations of [CHERI][]. Low-bit tagging
282 //! is very robust, and often doesn't even go out of bounds because types have a
283 //! size >= align (and over-aligning actually gives CHERI more flexibility). Anything
284 //! more complex than this rapidly enters "extremely platform-specific" territory as
285 //! certain things may or may not be allowed based on specific supported operations.
286 //! For instance, ARM explicitly supports high-bit tagging, and so CHERI on ARM inherits
287 //! that and should support it.
290 //! [aliasing]: ../../nomicon/aliasing.html
291 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
292 //! [ub]: ../../reference/behavior-considered-undefined.html
293 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
294 //! [atomic operations]: crate::sync::atomic
295 //! [`offset`]: pointer::offset
296 //! [`wrapping_offset`]: pointer::offset
297 //! [`with_addr`]: pointer::with_addr
298 //! [`map_addr`]: pointer::map_addr
299 //! [`addr`]: pointer::addr
300 //! [`ptr::invalid`]: core::ptr::invalid
301 //! [miri]: https://github.com/rust-lang/miri
302 //! [CHERI]: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
303 //! [Strict Provenance]: https://github.com/rust-lang/rust/issues/95228
304 //! [Stacked Borrows]: https://plv.mpi-sws.org/rustbelt/stacked-borrows/
306 #![stable(feature = "rust1", since = "1.0.0")]
308 use crate::cmp::Ordering;
311 use crate::intrinsics::{self, abort, is_aligned_and_not_null};
312 use crate::mem::{self, MaybeUninit};
314 #[stable(feature = "rust1", since = "1.0.0")]
316 pub use crate::intrinsics::copy_nonoverlapping;
318 #[stable(feature = "rust1", since = "1.0.0")]
320 pub use crate::intrinsics::copy;
322 #[stable(feature = "rust1", since = "1.0.0")]
324 pub use crate::intrinsics::write_bytes;
327 pub(crate) use metadata::PtrRepr;
328 #[unstable(feature = "ptr_metadata", issue = "81513")]
329 pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin};
332 #[stable(feature = "nonnull", since = "1.25.0")]
333 pub use non_null::NonNull;
336 #[unstable(feature = "ptr_internals", issue = "none")]
337 pub use unique::Unique;
342 /// Executes the destructor (if any) of the pointed-to value.
344 /// This is semantically equivalent to calling [`ptr::read`] and discarding
345 /// the result, but has the following advantages:
347 /// * It is *required* to use `drop_in_place` to drop unsized types like
348 /// trait objects, because they can't be read out onto the stack and
349 /// dropped normally.
351 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
352 /// dropping manually allocated memory (e.g., in the implementations of
353 /// `Box`/`Rc`/`Vec`), as the compiler doesn't need to prove that it's
354 /// sound to elide the copy.
356 /// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
357 /// (pinned data must not be moved before it is dropped).
359 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
360 /// location first using [`ptr::read_unaligned`]. For packed structs, this move is
361 /// done automatically by the compiler. This means the fields of packed structs
362 /// are not dropped in-place.
364 /// [`ptr::read`]: self::read
365 /// [`ptr::read_unaligned`]: self::read_unaligned
366 /// [pinned]: crate::pin
370 /// Behavior is undefined if any of the following conditions are violated:
372 /// * `to_drop` must be [valid] for both reads and writes.
374 /// * `to_drop` must be properly aligned.
376 /// * The value `to_drop` points to must be valid for dropping, which may mean it must uphold
377 /// additional invariants - this is type-dependent.
379 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
380 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
381 /// foo` counts as a use because it will cause the value to be dropped
382 /// again. [`write()`] can be used to overwrite data without causing it to be
385 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
387 /// [valid]: self#safety
391 /// Manually remove the last item from a vector:
397 /// let last = Rc::new(1);
398 /// let weak = Rc::downgrade(&last);
400 /// let mut v = vec![Rc::new(0), last];
403 /// // Get a raw pointer to the last element in `v`.
404 /// let ptr = &mut v[1] as *mut _;
405 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
406 /// // to prevent issues if the `drop_in_place` below panics.
408 /// // Without a call `drop_in_place`, the last item would never be dropped,
409 /// // and the memory it manages would be leaked.
410 /// ptr::drop_in_place(ptr);
413 /// assert_eq!(v, &[0.into()]);
415 /// // Ensure that the last item was dropped.
416 /// assert!(weak.upgrade().is_none());
418 #[stable(feature = "drop_in_place", since = "1.8.0")]
419 #[lang = "drop_in_place"]
420 #[allow(unconditional_recursion)]
421 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
422 // Code here does not matter - this is replaced by the
423 // real drop glue by the compiler.
425 // SAFETY: see comment above
426 unsafe { drop_in_place(to_drop) }
429 /// Creates a null raw pointer.
436 /// let p: *const i32 = ptr::null();
437 /// assert!(p.is_null());
441 #[stable(feature = "rust1", since = "1.0.0")]
443 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
444 #[rustc_diagnostic_item = "ptr_null"]
445 pub const fn null<T>() -> *const T {
449 /// Creates a null mutable raw pointer.
456 /// let p: *mut i32 = ptr::null_mut();
457 /// assert!(p.is_null());
461 #[stable(feature = "rust1", since = "1.0.0")]
463 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
464 #[rustc_diagnostic_item = "ptr_null_mut"]
465 pub const fn null_mut<T>() -> *mut T {
469 /// Creates an invalid pointer with the given address.
471 /// This is *currently* equivalent to `addr as *const T` but it expresses the intended semantic
472 /// more clearly, and may become important under future memory models.
474 /// The module's top-level documentation discusses the precise meaning of an "invalid"
475 /// pointer but essentially this expresses that the pointer is not associated
476 /// with any actual allocation and is little more than a usize address in disguise.
478 /// This pointer will have no provenance associated with it and is therefore
479 /// UB to read/write/offset. This mostly exists to facilitate things
480 /// like ptr::null and NonNull::dangling which make invalid pointers.
482 /// (Standard "Zero-Sized-Types get to cheat and lie" caveats apply, although it
483 /// may be desirable to give them their own API just to make that 100% clear.)
485 /// This API and its claimed semantics are part of the Strict Provenance experiment,
486 /// see the [module documentation][crate::ptr] for details.
489 #[rustc_const_stable(feature = "strict_provenance", since = "1.61.0")]
490 #[unstable(feature = "strict_provenance", issue = "95228")]
491 pub const fn invalid<T>(addr: usize) -> *const T {
492 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
496 /// Creates an invalid mutable pointer with the given address.
498 /// This is *currently* equivalent to `addr as *mut T` but it expresses the intended semantic
499 /// more clearly, and may become important under future memory models.
501 /// The module's top-level documentation discusses the precise meaning of an "invalid"
502 /// pointer but essentially this expresses that the pointer is not associated
503 /// with any actual allocation and is little more than a usize address in disguise.
505 /// This pointer will have no provenance associated with it and is therefore
506 /// UB to read/write/offset. This mostly exists to facilitate things
507 /// like ptr::null and NonNull::dangling which make invalid pointers.
509 /// (Standard "Zero-Sized-Types get to cheat and lie" caveats apply, although it
510 /// may be desirable to give them their own API just to make that 100% clear.)
512 /// This API and its claimed semantics are part of the Strict Provenance experiment,
513 /// see the [module documentation][crate::ptr] for details.
516 #[rustc_const_stable(feature = "strict_provenance", since = "1.61.0")]
517 #[unstable(feature = "strict_provenance", issue = "95228")]
518 pub const fn invalid_mut<T>(addr: usize) -> *mut T {
519 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
523 /// Forms a raw slice from a pointer and a length.
525 /// The `len` argument is the number of **elements**, not the number of bytes.
527 /// This function is safe, but actually using the return value is unsafe.
528 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
530 /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
537 /// // create a slice pointer when starting out with a pointer to the first element
538 /// let x = [5, 6, 7];
539 /// let raw_pointer = x.as_ptr();
540 /// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
541 /// assert_eq!(unsafe { &*slice }[2], 7);
544 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
545 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
546 pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
547 from_raw_parts(data.cast(), len)
550 /// Performs the same functionality as [`slice_from_raw_parts`], except that a
551 /// raw mutable slice is returned, as opposed to a raw immutable slice.
553 /// See the documentation of [`slice_from_raw_parts`] for more details.
555 /// This function is safe, but actually using the return value is unsafe.
556 /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
558 /// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
565 /// let x = &mut [5, 6, 7];
566 /// let raw_pointer = x.as_mut_ptr();
567 /// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
570 /// (*slice)[2] = 99; // assign a value at an index in the slice
573 /// assert_eq!(unsafe { &*slice }[2], 99);
576 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
577 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
578 pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
579 from_raw_parts_mut(data.cast(), len)
582 /// Swaps the values at two mutable locations of the same type, without
583 /// deinitializing either.
585 /// But for the following two exceptions, this function is semantically
586 /// equivalent to [`mem::swap`]:
588 /// * It operates on raw pointers instead of references. When references are
589 /// available, [`mem::swap`] should be preferred.
591 /// * The two pointed-to values may overlap. If the values do overlap, then the
592 /// overlapping region of memory from `x` will be used. This is demonstrated
593 /// in the second example below.
597 /// Behavior is undefined if any of the following conditions are violated:
599 /// * Both `x` and `y` must be [valid] for both reads and writes.
601 /// * Both `x` and `y` must be properly aligned.
603 /// Note that even if `T` has size `0`, the pointers must be non-null and properly aligned.
605 /// [valid]: self#safety
609 /// Swapping two non-overlapping regions:
614 /// let mut array = [0, 1, 2, 3];
616 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
617 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
621 /// assert_eq!([2, 3, 0, 1], array);
625 /// Swapping two overlapping regions:
630 /// let mut array: [i32; 4] = [0, 1, 2, 3];
632 /// let array_ptr: *mut i32 = array.as_mut_ptr();
634 /// let x = array_ptr as *mut [i32; 3]; // this is `array[0..3]`
635 /// let y = unsafe { array_ptr.add(1) } as *mut [i32; 3]; // this is `array[1..4]`
639 /// // The indices `1..3` of the slice overlap between `x` and `y`.
640 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
641 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
642 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
643 /// // This implementation is defined to make the latter choice.
644 /// assert_eq!([1, 0, 1, 2], array);
648 #[stable(feature = "rust1", since = "1.0.0")]
649 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
650 pub const unsafe fn swap<T>(x: *mut T, y: *mut T) {
651 // Give ourselves some scratch space to work with.
652 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
653 let mut tmp = MaybeUninit::<T>::uninit();
656 // SAFETY: the caller must guarantee that `x` and `y` are
657 // valid for writes and properly aligned. `tmp` cannot be
658 // overlapping either `x` or `y` because `tmp` was just allocated
659 // on the stack as a separate allocated object.
661 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
662 copy(y, x, 1); // `x` and `y` may overlap
663 copy_nonoverlapping(tmp.as_ptr(), y, 1);
667 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
668 /// beginning at `x` and `y`. The two regions must *not* overlap.
672 /// Behavior is undefined if any of the following conditions are violated:
674 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
675 /// size_of::<T>()` bytes.
677 /// * Both `x` and `y` must be properly aligned.
679 /// * The region of memory beginning at `x` with a size of `count *
680 /// size_of::<T>()` bytes must *not* overlap with the region of memory
681 /// beginning at `y` with the same size.
683 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
684 /// the pointers must be non-null and properly aligned.
686 /// [valid]: self#safety
695 /// let mut x = [1, 2, 3, 4];
696 /// let mut y = [7, 8, 9];
699 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
702 /// assert_eq!(x, [7, 8, 3, 4]);
703 /// assert_eq!(y, [1, 2, 9]);
706 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
707 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
708 pub const unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
710 macro_rules! attempt_swap_as_chunks {
712 if mem::align_of::<T>() >= mem::align_of::<$ChunkTy>()
713 && mem::size_of::<T>() % mem::size_of::<$ChunkTy>() == 0
715 let x: *mut MaybeUninit<$ChunkTy> = x.cast();
716 let y: *mut MaybeUninit<$ChunkTy> = y.cast();
717 let count = count * (mem::size_of::<T>() / mem::size_of::<$ChunkTy>());
718 // SAFETY: these are the same bytes that the caller promised were
719 // ok, just typed as `MaybeUninit<ChunkTy>`s instead of as `T`s.
720 // The `if` condition above ensures that we're not violating
721 // alignment requirements, and that the division is exact so
722 // that we don't lose any bytes off the end.
723 return unsafe { swap_nonoverlapping_simple(x, y, count) };
728 // NOTE(scottmcm) MIRI is disabled here as reading in smaller units is a
729 // pessimization for it. Also, if the type contains any unaligned pointers,
730 // copying those over multiple reads is difficult to support.
733 // Split up the slice into small power-of-two-sized chunks that LLVM is able
734 // to vectorize (unless it's a special type with more-than-pointer alignment,
735 // because we don't want to pessimize things like slices of SIMD vectors.)
736 if mem::align_of::<T>() <= mem::size_of::<usize>()
737 && (!mem::size_of::<T>().is_power_of_two()
738 || mem::size_of::<T>() > mem::size_of::<usize>() * 2)
740 attempt_swap_as_chunks!(usize);
741 attempt_swap_as_chunks!(u8);
745 // SAFETY: Same preconditions as this function
746 unsafe { swap_nonoverlapping_simple(x, y, count) }
749 /// Same behaviour and safety conditions as [`swap_nonoverlapping`]
751 /// LLVM can vectorize this (at least it can for the power-of-two-sized types
752 /// `swap_nonoverlapping` tries to use) so no need to manually SIMD it.
754 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
755 const unsafe fn swap_nonoverlapping_simple<T>(x: *mut T, y: *mut T, count: usize) {
759 // SAFETY: By precondition, `i` is in-bounds because it's below `n`
760 unsafe { &mut *x.add(i) };
762 // SAFETY: By precondition, `i` is in-bounds because it's below `n`
763 // and it's distinct from `x` since the ranges are non-overlapping
764 unsafe { &mut *y.add(i) };
765 mem::swap_simple(x, y);
771 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
773 /// Neither value is dropped.
775 /// This function is semantically equivalent to [`mem::replace`] except that it
776 /// operates on raw pointers instead of references. When references are
777 /// available, [`mem::replace`] should be preferred.
781 /// Behavior is undefined if any of the following conditions are violated:
783 /// * `dst` must be [valid] for both reads and writes.
785 /// * `dst` must be properly aligned.
787 /// * `dst` must point to a properly initialized value of type `T`.
789 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
791 /// [valid]: self#safety
798 /// let mut rust = vec!['b', 'u', 's', 't'];
800 /// // `mem::replace` would have the same effect without requiring the unsafe
803 /// ptr::replace(&mut rust[0], 'r')
806 /// assert_eq!(b, 'b');
807 /// assert_eq!(rust, &['r', 'u', 's', 't']);
810 #[stable(feature = "rust1", since = "1.0.0")]
811 #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
812 pub const unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
813 // SAFETY: the caller must guarantee that `dst` is valid to be
814 // cast to a mutable reference (valid for writes, aligned, initialized),
815 // and cannot overlap `src` since `dst` must point to a distinct
818 mem::swap(&mut *dst, &mut src); // cannot overlap
823 /// Reads the value from `src` without moving it. This leaves the
824 /// memory in `src` unchanged.
828 /// Behavior is undefined if any of the following conditions are violated:
830 /// * `src` must be [valid] for reads.
832 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
835 /// * `src` must point to a properly initialized value of type `T`.
837 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
845 /// let y = &x as *const i32;
848 /// assert_eq!(std::ptr::read(y), 12);
852 /// Manually implement [`mem::swap`]:
857 /// fn swap<T>(a: &mut T, b: &mut T) {
859 /// // Create a bitwise copy of the value at `a` in `tmp`.
860 /// let tmp = ptr::read(a);
862 /// // Exiting at this point (either by explicitly returning or by
863 /// // calling a function which panics) would cause the value in `tmp` to
864 /// // be dropped while the same value is still referenced by `a`. This
865 /// // could trigger undefined behavior if `T` is not `Copy`.
867 /// // Create a bitwise copy of the value at `b` in `a`.
868 /// // This is safe because mutable references cannot alias.
869 /// ptr::copy_nonoverlapping(b, a, 1);
871 /// // As above, exiting here could trigger undefined behavior because
872 /// // the same value is referenced by `a` and `b`.
874 /// // Move `tmp` into `b`.
875 /// ptr::write(b, tmp);
877 /// // `tmp` has been moved (`write` takes ownership of its second argument),
878 /// // so nothing is dropped implicitly here.
882 /// let mut foo = "foo".to_owned();
883 /// let mut bar = "bar".to_owned();
885 /// swap(&mut foo, &mut bar);
887 /// assert_eq!(foo, "bar");
888 /// assert_eq!(bar, "foo");
891 /// ## Ownership of the Returned Value
893 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
894 /// If `T` is not [`Copy`], using both the returned value and the value at
895 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
896 /// use because it will attempt to drop the value at `*src`.
898 /// [`write()`] can be used to overwrite data without causing it to be dropped.
903 /// let mut s = String::from("foo");
905 /// // `s2` now points to the same underlying memory as `s`.
906 /// let mut s2: String = ptr::read(&s);
908 /// assert_eq!(s2, "foo");
910 /// // Assigning to `s2` causes its original value to be dropped. Beyond
911 /// // this point, `s` must no longer be used, as the underlying memory has
913 /// s2 = String::default();
914 /// assert_eq!(s2, "");
916 /// // Assigning to `s` would cause the old value to be dropped again,
917 /// // resulting in undefined behavior.
918 /// // s = String::from("bar"); // ERROR
920 /// // `ptr::write` can be used to overwrite a value without dropping it.
921 /// ptr::write(&mut s, String::from("bar"));
924 /// assert_eq!(s, "bar");
927 /// [valid]: self#safety
929 #[stable(feature = "rust1", since = "1.0.0")]
930 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
931 pub const unsafe fn read<T>(src: *const T) -> T {
932 // We are calling the intrinsics directly to avoid function calls in the generated code
933 // as `intrinsics::copy_nonoverlapping` is a wrapper function.
934 extern "rust-intrinsic" {
935 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
936 fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
939 let mut tmp = MaybeUninit::<T>::uninit();
940 // SAFETY: the caller must guarantee that `src` is valid for reads.
941 // `src` cannot overlap `tmp` because `tmp` was just allocated on
942 // the stack as a separate allocated object.
944 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
945 // to be properly initialized.
947 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
952 /// Reads the value from `src` without moving it. This leaves the
953 /// memory in `src` unchanged.
955 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
959 /// Behavior is undefined if any of the following conditions are violated:
961 /// * `src` must be [valid] for reads.
963 /// * `src` must point to a properly initialized value of type `T`.
965 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
966 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
967 /// value and the value at `*src` can [violate memory safety][read-ownership].
969 /// Note that even if `T` has size `0`, the pointer must be non-null.
971 /// [read-ownership]: read#ownership-of-the-returned-value
972 /// [valid]: self#safety
974 /// ## On `packed` structs
976 /// Attempting to create a raw pointer to an `unaligned` struct field with
977 /// an expression such as `&packed.unaligned as *const FieldType` creates an
978 /// intermediate unaligned reference before converting that to a raw pointer.
979 /// That this reference is temporary and immediately cast is inconsequential
980 /// as the compiler always expects references to be properly aligned.
981 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
982 /// *undefined behavior* in your program.
984 /// Instead you must use the [`ptr::addr_of!`](addr_of) macro to
985 /// create the pointer. You may use that returned pointer together with this
988 /// An example of what not to do and how this relates to `read_unaligned` is:
991 /// #[repr(packed, C)]
997 /// let packed = Packed {
999 /// unaligned: 0x01020304,
1002 /// // Take the address of a 32-bit integer which is not aligned.
1003 /// // In contrast to `&packed.unaligned as *const _`, this has no undefined behavior.
1004 /// let unaligned = std::ptr::addr_of!(packed.unaligned);
1006 /// let v = unsafe { std::ptr::read_unaligned(unaligned) };
1007 /// assert_eq!(v, 0x01020304);
1010 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
1014 /// Read a usize value from a byte buffer:
1019 /// fn read_usize(x: &[u8]) -> usize {
1020 /// assert!(x.len() >= mem::size_of::<usize>());
1022 /// let ptr = x.as_ptr() as *const usize;
1024 /// unsafe { ptr.read_unaligned() }
1028 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
1029 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1030 pub const unsafe fn read_unaligned<T>(src: *const T) -> T {
1031 let mut tmp = MaybeUninit::<T>::uninit();
1032 // SAFETY: the caller must guarantee that `src` is valid for reads.
1033 // `src` cannot overlap `tmp` because `tmp` was just allocated on
1034 // the stack as a separate allocated object.
1036 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
1037 // to be properly initialized.
1039 copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::<T>());
1044 /// Overwrites a memory location with the given value without reading or
1045 /// dropping the old value.
1047 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
1048 /// allocations or resources, so care should be taken not to overwrite an object
1049 /// that should be dropped.
1051 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1052 /// location pointed to by `dst`.
1054 /// This is appropriate for initializing uninitialized memory, or overwriting
1055 /// memory that has previously been [`read`] from.
1059 /// Behavior is undefined if any of the following conditions are violated:
1061 /// * `dst` must be [valid] for writes.
1063 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
1066 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1068 /// [valid]: self#safety
1076 /// let y = &mut x as *mut i32;
1080 /// std::ptr::write(y, z);
1081 /// assert_eq!(std::ptr::read(y), 12);
1085 /// Manually implement [`mem::swap`]:
1090 /// fn swap<T>(a: &mut T, b: &mut T) {
1092 /// // Create a bitwise copy of the value at `a` in `tmp`.
1093 /// let tmp = ptr::read(a);
1095 /// // Exiting at this point (either by explicitly returning or by
1096 /// // calling a function which panics) would cause the value in `tmp` to
1097 /// // be dropped while the same value is still referenced by `a`. This
1098 /// // could trigger undefined behavior if `T` is not `Copy`.
1100 /// // Create a bitwise copy of the value at `b` in `a`.
1101 /// // This is safe because mutable references cannot alias.
1102 /// ptr::copy_nonoverlapping(b, a, 1);
1104 /// // As above, exiting here could trigger undefined behavior because
1105 /// // the same value is referenced by `a` and `b`.
1107 /// // Move `tmp` into `b`.
1108 /// ptr::write(b, tmp);
1110 /// // `tmp` has been moved (`write` takes ownership of its second argument),
1111 /// // so nothing is dropped implicitly here.
1115 /// let mut foo = "foo".to_owned();
1116 /// let mut bar = "bar".to_owned();
1118 /// swap(&mut foo, &mut bar);
1120 /// assert_eq!(foo, "bar");
1121 /// assert_eq!(bar, "foo");
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1126 pub const unsafe fn write<T>(dst: *mut T, src: T) {
1127 // We are calling the intrinsics directly to avoid function calls in the generated code
1128 // as `intrinsics::copy_nonoverlapping` is a wrapper function.
1129 extern "rust-intrinsic" {
1130 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1131 fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
1134 // SAFETY: the caller must guarantee that `dst` is valid for writes.
1135 // `dst` cannot overlap `src` because the caller has mutable access
1136 // to `dst` while `src` is owned by this function.
1138 copy_nonoverlapping(&src as *const T, dst, 1);
1139 intrinsics::forget(src);
1143 /// Overwrites a memory location with the given value without reading or
1144 /// dropping the old value.
1146 /// Unlike [`write()`], the pointer may be unaligned.
1148 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
1149 /// could leak allocations or resources, so care should be taken not to overwrite
1150 /// an object that should be dropped.
1152 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1153 /// location pointed to by `dst`.
1155 /// This is appropriate for initializing uninitialized memory, or overwriting
1156 /// memory that has previously been read with [`read_unaligned`].
1160 /// Behavior is undefined if any of the following conditions are violated:
1162 /// * `dst` must be [valid] for writes.
1164 /// Note that even if `T` has size `0`, the pointer must be non-null.
1166 /// [valid]: self#safety
1168 /// ## On `packed` structs
1170 /// Attempting to create a raw pointer to an `unaligned` struct field with
1171 /// an expression such as `&packed.unaligned as *const FieldType` creates an
1172 /// intermediate unaligned reference before converting that to a raw pointer.
1173 /// That this reference is temporary and immediately cast is inconsequential
1174 /// as the compiler always expects references to be properly aligned.
1175 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
1176 /// *undefined behavior* in your program.
1178 /// Instead you must use the [`ptr::addr_of_mut!`](addr_of_mut)
1179 /// macro to create the pointer. You may use that returned pointer together with
1182 /// An example of how to do it and how this relates to `write_unaligned` is:
1185 /// #[repr(packed, C)]
1191 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
1193 /// // Take the address of a 32-bit integer which is not aligned.
1194 /// // In contrast to `&packed.unaligned as *mut _`, this has no undefined behavior.
1195 /// let unaligned = std::ptr::addr_of_mut!(packed.unaligned);
1197 /// unsafe { std::ptr::write_unaligned(unaligned, 42) };
1199 /// assert_eq!({packed.unaligned}, 42); // `{...}` forces copying the field instead of creating a reference.
1202 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however
1203 /// (as can be seen in the `assert_eq!` above).
1207 /// Write a usize value to a byte buffer:
1212 /// fn write_usize(x: &mut [u8], val: usize) {
1213 /// assert!(x.len() >= mem::size_of::<usize>());
1215 /// let ptr = x.as_mut_ptr() as *mut usize;
1217 /// unsafe { ptr.write_unaligned(val) }
1221 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
1222 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1223 pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
1224 // SAFETY: the caller must guarantee that `dst` is valid for writes.
1225 // `dst` cannot overlap `src` because the caller has mutable access
1226 // to `dst` while `src` is owned by this function.
1228 copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::<T>());
1229 // We are calling the intrinsic directly to avoid function calls in the generated code.
1230 intrinsics::forget(src);
1234 /// Performs a volatile read of the value from `src` without moving it. This
1235 /// leaves the memory in `src` unchanged.
1237 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1238 /// to not be elided or reordered by the compiler across other volatile
1243 /// Rust does not currently have a rigorously and formally defined memory model,
1244 /// so the precise semantics of what "volatile" means here is subject to change
1245 /// over time. That being said, the semantics will almost always end up pretty
1246 /// similar to [C11's definition of volatile][c11].
1248 /// The compiler shouldn't change the relative order or number of volatile
1249 /// memory operations. However, volatile memory operations on zero-sized types
1250 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
1251 /// and may be ignored.
1253 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1257 /// Behavior is undefined if any of the following conditions are violated:
1259 /// * `src` must be [valid] for reads.
1261 /// * `src` must be properly aligned.
1263 /// * `src` must point to a properly initialized value of type `T`.
1265 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
1266 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1267 /// value and the value at `*src` can [violate memory safety][read-ownership].
1268 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
1271 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1273 /// [valid]: self#safety
1274 /// [read-ownership]: read#ownership-of-the-returned-value
1276 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1277 /// on questions involving concurrent access from multiple threads. Volatile
1278 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1279 /// a race between a `read_volatile` and any write operation to the same location
1280 /// is undefined behavior.
1288 /// let y = &x as *const i32;
1291 /// assert_eq!(std::ptr::read_volatile(y), 12);
1295 #[stable(feature = "volatile", since = "1.9.0")]
1296 pub unsafe fn read_volatile<T>(src: *const T) -> T {
1297 if cfg!(debug_assertions) && !is_aligned_and_not_null(src) {
1298 // Not panicking to keep codegen impact smaller.
1301 // SAFETY: the caller must uphold the safety contract for `volatile_load`.
1302 unsafe { intrinsics::volatile_load(src) }
1305 /// Performs a volatile write of a memory location with the given value without
1306 /// reading or dropping the old value.
1308 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1309 /// to not be elided or reordered by the compiler across other volatile
1312 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
1313 /// could leak allocations or resources, so care should be taken not to overwrite
1314 /// an object that should be dropped.
1316 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1317 /// location pointed to by `dst`.
1321 /// Rust does not currently have a rigorously and formally defined memory model,
1322 /// so the precise semantics of what "volatile" means here is subject to change
1323 /// over time. That being said, the semantics will almost always end up pretty
1324 /// similar to [C11's definition of volatile][c11].
1326 /// The compiler shouldn't change the relative order or number of volatile
1327 /// memory operations. However, volatile memory operations on zero-sized types
1328 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
1329 /// and may be ignored.
1331 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1335 /// Behavior is undefined if any of the following conditions are violated:
1337 /// * `dst` must be [valid] for writes.
1339 /// * `dst` must be properly aligned.
1341 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1343 /// [valid]: self#safety
1345 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1346 /// on questions involving concurrent access from multiple threads. Volatile
1347 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1348 /// a race between a `write_volatile` and any other operation (reading or writing)
1349 /// on the same location is undefined behavior.
1357 /// let y = &mut x as *mut i32;
1361 /// std::ptr::write_volatile(y, z);
1362 /// assert_eq!(std::ptr::read_volatile(y), 12);
1366 #[stable(feature = "volatile", since = "1.9.0")]
1367 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
1368 if cfg!(debug_assertions) && !is_aligned_and_not_null(dst) {
1369 // Not panicking to keep codegen impact smaller.
1372 // SAFETY: the caller must uphold the safety contract for `volatile_store`.
1374 intrinsics::volatile_store(dst, src);
1378 /// Align pointer `p`.
1380 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
1381 /// to pointer `p` so that pointer `p` would get aligned to `a`.
1383 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
1384 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
1387 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
1388 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
1389 /// than trying to adapt this to accommodate that change.
1391 /// Any questions go to @nagisa.
1392 #[lang = "align_offset"]
1393 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
1394 // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
1395 // 1, where the method versions of these operations are not inlined.
1397 unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub,
1400 let addr = p.addr();
1402 /// Calculate multiplicative modular inverse of `x` modulo `m`.
1404 /// This implementation is tailored for `align_offset` and has following preconditions:
1406 /// * `m` is a power-of-two;
1407 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1409 /// Implementation of this function shall not panic. Ever.
1411 unsafe fn mod_inv(x: usize, m: usize) -> usize {
1412 /// Multiplicative modular inverse table modulo 2⁴ = 16.
1414 /// Note, that this table does not contain values where inverse does not exist (i.e., for
1415 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
1416 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
1417 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
1418 const INV_TABLE_MOD: usize = 16;
1420 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
1422 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
1423 // SAFETY: `m` is required to be a power-of-two, hence non-zero.
1424 let m_minus_one = unsafe { unchecked_sub(m, 1) };
1425 if m <= INV_TABLE_MOD {
1426 table_inverse & m_minus_one
1428 // We iterate "up" using the following formula:
1430 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1432 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
1433 let mut inverse = table_inverse;
1434 let mut going_mod = INV_TABLE_MOD_SQUARED;
1436 // y = y * (2 - xy) mod n
1438 // Note, that we use wrapping operations here intentionally – the original formula
1439 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
1440 // usize::MAX` instead, because we take the result `mod n` at the end
1442 inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse)));
1444 return inverse & m_minus_one;
1446 going_mod = wrapping_mul(going_mod, going_mod);
1451 let stride = mem::size_of::<T>();
1452 // SAFETY: `a` is a power-of-two, therefore non-zero.
1453 let a_minus_one = unsafe { unchecked_sub(a, 1) };
1455 // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so
1456 // inhibits LLVM's ability to select instructions like `lea`. Instead we compute
1458 // round_up_to_next_alignment(p, a) - p
1460 // which distributes operations around the load-bearing, but pessimizing `and` sufficiently
1461 // for LLVM to be able to utilize the various optimizations it knows about.
1462 return wrapping_sub(wrapping_add(addr, a_minus_one) & wrapping_sub(0, a), addr);
1465 let pmoda = addr & a_minus_one;
1467 // Already aligned. Yay!
1469 } else if stride == 0 {
1470 // If the pointer is not aligned, and the element is zero-sized, then no amount of
1471 // elements will ever align the pointer.
1475 let smoda = stride & a_minus_one;
1476 // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
1477 let gcdpow = unsafe { intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)) };
1478 // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize.
1479 let gcd = unsafe { unchecked_shl(1usize, gcdpow) };
1481 // SAFETY: gcd is always greater or equal to 1.
1482 if addr & unsafe { unchecked_sub(gcd, 1) } == 0 {
1483 // This branch solves for the following linear congruence equation:
1485 // ` p + so = 0 mod a `
1487 // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1488 // requested alignment.
1490 // With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
1491 // `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1493 // ` p' + s'o = 0 mod a' `
1494 // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1496 // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the second
1497 // term is "how does incrementing `p` by `s` bytes change the relative alignment of `p`" (again
1499 // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1502 // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1503 // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`.
1505 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1507 let a2 = unsafe { unchecked_shr(a, gcdpow) };
1508 // SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
1509 // in `a` (of which it has exactly one).
1510 let a2minus1 = unsafe { unchecked_sub(a2, 1) };
1511 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1513 let s2 = unsafe { unchecked_shr(smoda, gcdpow) };
1514 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1515 // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
1516 // always be strictly greater than `(p % a) >> gcdpow`.
1517 let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(pmoda, gcdpow)) };
1518 // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
1519 // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
1520 return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;
1523 // Cannot be aligned at all.
1527 /// Compares raw pointers for equality.
1529 /// This is the same as using the `==` operator, but less generic:
1530 /// the arguments have to be `*const T` raw pointers,
1531 /// not anything that implements `PartialEq`.
1533 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
1534 /// by their address rather than comparing the values they point to
1535 /// (which is what the `PartialEq for &T` implementation does).
1543 /// let other_five = 5;
1544 /// let five_ref = &five;
1545 /// let same_five_ref = &five;
1546 /// let other_five_ref = &other_five;
1548 /// assert!(five_ref == same_five_ref);
1549 /// assert!(ptr::eq(five_ref, same_five_ref));
1551 /// assert!(five_ref == other_five_ref);
1552 /// assert!(!ptr::eq(five_ref, other_five_ref));
1555 /// Slices are also compared by their length (fat pointers):
1558 /// let a = [1, 2, 3];
1559 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
1560 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
1561 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
1564 /// Traits are also compared by their implementation:
1567 /// #[repr(transparent)]
1568 /// struct Wrapper { member: i32 }
1571 /// impl Trait for Wrapper {}
1572 /// impl Trait for i32 {}
1574 /// let wrapper = Wrapper { member: 10 };
1576 /// // Pointers have equal addresses.
1577 /// assert!(std::ptr::eq(
1578 /// &wrapper as *const Wrapper as *const u8,
1579 /// &wrapper.member as *const i32 as *const u8
1582 /// // Objects have equal addresses, but `Trait` has different implementations.
1583 /// assert!(!std::ptr::eq(
1584 /// &wrapper as &dyn Trait,
1585 /// &wrapper.member as &dyn Trait,
1587 /// assert!(!std::ptr::eq(
1588 /// &wrapper as &dyn Trait as *const dyn Trait,
1589 /// &wrapper.member as &dyn Trait as *const dyn Trait,
1592 /// // Converting the reference to a `*const u8` compares by address.
1593 /// assert!(std::ptr::eq(
1594 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
1595 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
1598 #[stable(feature = "ptr_eq", since = "1.17.0")]
1600 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
1604 /// Hash a raw pointer.
1606 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
1607 /// by its address rather than the value it points to
1608 /// (which is what the `Hash for &T` implementation does).
1613 /// use std::collections::hash_map::DefaultHasher;
1614 /// use std::hash::{Hash, Hasher};
1618 /// let five_ref = &five;
1620 /// let mut hasher = DefaultHasher::new();
1621 /// ptr::hash(five_ref, &mut hasher);
1622 /// let actual = hasher.finish();
1624 /// let mut hasher = DefaultHasher::new();
1625 /// (five_ref as *const i32).hash(&mut hasher);
1626 /// let expected = hasher.finish();
1628 /// assert_eq!(actual, expected);
1630 #[stable(feature = "ptr_hash", since = "1.35.0")]
1631 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
1632 use crate::hash::Hash;
1636 // FIXME(strict_provenance_magic): function pointers have buggy codegen that
1637 // necessitates casting to a usize to get the backend to do the right thing.
1638 // for now I will break AVR to silence *a billion* lints. We should probably
1639 // have a proper "opaque function pointer type" to handle this kind of thing.
1641 // Impls for function pointers
1642 macro_rules! fnptr_impls_safety_abi {
1643 ($FnTy: ty, $($Arg: ident),*) => {
1644 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1645 impl<Ret, $($Arg),*> PartialEq for $FnTy {
1647 fn eq(&self, other: &Self) -> bool {
1648 *self as usize == *other as usize
1652 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1653 impl<Ret, $($Arg),*> Eq for $FnTy {}
1655 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1656 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
1658 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1659 (*self as usize).partial_cmp(&(*other as usize))
1663 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1664 impl<Ret, $($Arg),*> Ord for $FnTy {
1666 fn cmp(&self, other: &Self) -> Ordering {
1667 (*self as usize).cmp(&(*other as usize))
1671 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1672 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
1673 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
1674 state.write_usize(*self as usize)
1678 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1679 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
1680 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1681 // HACK: The intermediate cast as usize is required for AVR
1682 // so that the address space of the source function pointer
1683 // is preserved in the final function pointer.
1685 // https://github.com/avr-rust/rust/issues/143
1686 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1690 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1691 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
1692 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1693 // HACK: The intermediate cast as usize is required for AVR
1694 // so that the address space of the source function pointer
1695 // is preserved in the final function pointer.
1697 // https://github.com/avr-rust/rust/issues/143
1698 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1704 macro_rules! fnptr_impls_args {
1705 ($($Arg: ident),+) => {
1706 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1707 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1708 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1709 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1710 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1711 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1714 // No variadic functions with 0 parameters
1715 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
1716 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
1717 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
1718 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
1722 fnptr_impls_args! {}
1723 fnptr_impls_args! { A }
1724 fnptr_impls_args! { A, B }
1725 fnptr_impls_args! { A, B, C }
1726 fnptr_impls_args! { A, B, C, D }
1727 fnptr_impls_args! { A, B, C, D, E }
1728 fnptr_impls_args! { A, B, C, D, E, F }
1729 fnptr_impls_args! { A, B, C, D, E, F, G }
1730 fnptr_impls_args! { A, B, C, D, E, F, G, H }
1731 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
1732 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
1733 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
1734 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
1736 /// Create a `const` raw pointer to a place, without creating an intermediate reference.
1738 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1739 /// and points to initialized data. For cases where those requirements do not hold,
1740 /// raw pointers should be used instead. However, `&expr as *const _` creates a reference
1741 /// before casting it to a raw pointer, and that reference is subject to the same rules
1742 /// as all other references. This macro can create a raw pointer *without* creating
1743 /// a reference first.
1745 /// Note, however, that the `expr` in `addr_of!(expr)` is still subject to all
1746 /// the usual rules. In particular, `addr_of!(*ptr::null())` is Undefined
1747 /// Behavior because it dereferences a null pointer.
1760 /// let packed = Packed { f1: 1, f2: 2 };
1761 /// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1762 /// let raw_f2 = ptr::addr_of!(packed.f2);
1763 /// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
1766 /// See [`addr_of_mut`] for how to create a pointer to unininitialized data.
1767 /// Doing that with `addr_of` would not make much sense since one could only
1768 /// read the data, and that would be Undefined Behavior.
1769 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1770 #[rustc_macro_transparency = "semitransparent"]
1771 #[allow_internal_unstable(raw_ref_op)]
1772 pub macro addr_of($place:expr) {
1776 /// Create a `mut` raw pointer to a place, without creating an intermediate reference.
1778 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1779 /// and points to initialized data. For cases where those requirements do not hold,
1780 /// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
1781 /// before casting it to a raw pointer, and that reference is subject to the same rules
1782 /// as all other references. This macro can create a raw pointer *without* creating
1783 /// a reference first.
1785 /// Note, however, that the `expr` in `addr_of_mut!(expr)` is still subject to all
1786 /// the usual rules. In particular, `addr_of_mut!(*ptr::null_mut())` is Undefined
1787 /// Behavior because it dereferences a null pointer.
1791 /// **Creating a pointer to unaligned data:**
1802 /// let mut packed = Packed { f1: 1, f2: 2 };
1803 /// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1804 /// let raw_f2 = ptr::addr_of_mut!(packed.f2);
1805 /// unsafe { raw_f2.write_unaligned(42); }
1806 /// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
1809 /// **Creating a pointer to uninitialized data:**
1812 /// use std::{ptr, mem::MaybeUninit};
1818 /// let mut uninit = MaybeUninit::<Demo>::uninit();
1819 /// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
1820 /// // and thus be Undefined Behavior!
1821 /// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
1822 /// unsafe { f1_ptr.write(true); }
1823 /// let init = unsafe { uninit.assume_init() };
1825 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1826 #[rustc_macro_transparency = "semitransparent"]
1827 #[allow_internal_unstable(raw_ref_op)]
1828 pub macro addr_of_mut($place:expr) {