1 //! Manually manage memory through raw pointers.
3 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
7 //! Many functions in this module take raw pointers as arguments and read from
8 //! or write to them. For this to be safe, these pointers must be *valid*.
9 //! Whether a pointer is valid depends on the operation it is used for
10 //! (read or write), and the extent of the memory that is accessed (i.e.,
11 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
12 //! to access only a single value, in which case the documentation omits the size
13 //! and implicitly assumes it to be `size_of::<T>()` bytes.
15 //! The precise rules for validity are not determined yet. The guarantees that are
16 //! provided at this point are very minimal:
18 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
19 //! * All pointers (except for the null pointer) are valid for all operations of
21 //! * For a pointer to be valid, it is necessary, but not always sufficient, that the pointer
22 //! be *dereferenceable*: the memory range of the given size starting at the pointer must all be
23 //! within the bounds of a single allocated object. Note that in Rust,
24 //! every (stack-allocated) variable is considered a separate allocated object.
25 //! * All accesses performed by functions in this module are *non-atomic* in the sense
26 //! of [atomic operations] used to synchronize between threads. This means it is
27 //! undefined behavior to perform two concurrent accesses to the same location from different
28 //! threads unless both accesses only read from memory. Notice that this explicitly
29 //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
30 //! be used for inter-thread synchronization.
31 //! * The result of casting a reference to a pointer is valid for as long as the
32 //! underlying object is live and no reference (just raw pointers) is used to
33 //! access the same memory.
35 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
36 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
37 //! will be provided eventually, as the [aliasing] rules are being determined. For more
38 //! information, see the [book] as well as the section in the reference devoted
39 //! to [undefined behavior][ub].
43 //! Valid raw pointers as defined above are not necessarily properly aligned (where
44 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
45 //! aligned to `mem::align_of::<T>()`). However, most functions require their
46 //! arguments to be properly aligned, and will explicitly state
47 //! this requirement in their documentation. Notable exceptions to this are
48 //! [`read_unaligned`] and [`write_unaligned`].
50 //! When a function requires proper alignment, it does so even if the access
51 //! has size 0, i.e., even if memory is not actually touched. Consider using
52 //! [`NonNull::dangling`] in such cases.
54 //! [aliasing]: ../../nomicon/aliasing.html
55 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
56 //! [ub]: ../../reference/behavior-considered-undefined.html
57 //! [null]: ./fn.null.html
58 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
59 //! [atomic operations]: ../../std/sync/atomic/index.html
60 //! [`copy`]: ../../std/ptr/fn.copy.html
61 //! [`offset`]: ../../std/primitive.pointer.html#method.offset
62 //! [`read_unaligned`]: ./fn.read_unaligned.html
63 //! [`write_unaligned`]: ./fn.write_unaligned.html
64 //! [`read_volatile`]: ./fn.read_volatile.html
65 //! [`write_volatile`]: ./fn.write_volatile.html
66 //! [`NonNull::dangling`]: ./struct.NonNull.html#method.dangling
68 // ignore-tidy-undocumented-unsafe
70 #![stable(feature = "rust1", since = "1.0.0")]
72 use crate::cmp::Ordering;
75 use crate::intrinsics::{self, is_aligned_and_not_null, is_nonoverlapping};
76 use crate::mem::{self, MaybeUninit};
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use crate::intrinsics::copy_nonoverlapping;
81 #[stable(feature = "rust1", since = "1.0.0")]
82 pub use crate::intrinsics::copy;
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub use crate::intrinsics::write_bytes;
88 #[stable(feature = "nonnull", since = "1.25.0")]
89 pub use non_null::NonNull;
92 #[unstable(feature = "ptr_internals", issue = "none")]
93 pub use unique::Unique;
98 /// Executes the destructor (if any) of the pointed-to value.
100 /// This is semantically equivalent to calling [`ptr::read`] and discarding
101 /// the result, but has the following advantages:
103 /// * It is *required* to use `drop_in_place` to drop unsized types like
104 /// trait objects, because they can't be read out onto the stack and
105 /// dropped normally.
107 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
108 /// dropping manually allocated memory (e.g., when writing Box/Rc/Vec),
109 /// as the compiler doesn't need to prove that it's sound to elide the
112 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
113 /// location first using [`ptr::read_unaligned`].
115 /// [`ptr::read`]: ../ptr/fn.read.html
116 /// [`ptr::read_unaligned`]: ../ptr/fn.read_unaligned.html
120 /// Behavior is undefined if any of the following conditions are violated:
122 /// * `to_drop` must be [valid] for both reads and writes.
124 /// * `to_drop` must be properly aligned.
126 /// * The value `to_drop` points to must be valid for dropping, which may mean it must uphold
127 /// additional invariants - this is type-dependent.
129 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
130 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
131 /// foo` counts as a use because it will cause the value to be dropped
132 /// again. [`write`] can be used to overwrite data without causing it to be
135 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
137 /// [valid]: ../ptr/index.html#safety
138 /// [`Copy`]: ../marker/trait.Copy.html
139 /// [`write`]: ../ptr/fn.write.html
143 /// Manually remove the last item from a vector:
149 /// let last = Rc::new(1);
150 /// let weak = Rc::downgrade(&last);
152 /// let mut v = vec![Rc::new(0), last];
155 /// // Get a raw pointer to the last element in `v`.
156 /// let ptr = &mut v[1] as *mut _;
157 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
158 /// // to prevent issues if the `drop_in_place` below panics.
160 /// // Without a call `drop_in_place`, the last item would never be dropped,
161 /// // and the memory it manages would be leaked.
162 /// ptr::drop_in_place(ptr);
165 /// assert_eq!(v, &[0.into()]);
167 /// // Ensure that the last item was dropped.
168 /// assert!(weak.upgrade().is_none());
171 /// Notice that the compiler performs this copy automatically when dropping packed structs,
172 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
174 #[stable(feature = "drop_in_place", since = "1.8.0")]
175 #[lang = "drop_in_place"]
176 #[allow(unconditional_recursion)]
177 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
178 // Code here does not matter - this is replaced by the
179 // real drop glue by the compiler.
180 drop_in_place(to_drop)
183 /// Creates a null raw pointer.
190 /// let p: *const i32 = ptr::null();
191 /// assert!(p.is_null());
194 #[stable(feature = "rust1", since = "1.0.0")]
196 #[rustc_const_stable(feature = "const_ptr_null", since = "1.32.0")]
197 pub const fn null<T>() -> *const T {
201 /// Creates a null mutable raw pointer.
208 /// let p: *mut i32 = ptr::null_mut();
209 /// assert!(p.is_null());
212 #[stable(feature = "rust1", since = "1.0.0")]
214 #[rustc_const_stable(feature = "const_ptr_null", since = "1.32.0")]
215 pub const fn null_mut<T>() -> *mut T {
220 pub(crate) union Repr<T> {
221 pub(crate) rust: *const [T],
223 pub(crate) raw: FatPtr<T>,
227 pub(crate) struct FatPtr<T> {
229 pub(crate) len: usize,
232 /// Forms a raw slice from a pointer and a length.
234 /// The `len` argument is the number of **elements**, not the number of bytes.
236 /// This function is safe, but actually using the return value is unsafe.
237 /// See the documentation of [`from_raw_parts`] for slice safety requirements.
239 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
246 /// // create a slice pointer when starting out with a pointer to the first element
247 /// let x = [5, 6, 7];
248 /// let ptr = x.as_ptr();
249 /// let slice = ptr::slice_from_raw_parts(ptr, 3);
250 /// assert_eq!(unsafe { &*slice }[2], 7);
253 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
254 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
255 pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
256 unsafe { Repr { raw: FatPtr { data, len } }.rust }
259 /// Performs the same functionality as [`slice_from_raw_parts`], except that a
260 /// raw mutable slice is returned, as opposed to a raw immutable slice.
262 /// See the documentation of [`slice_from_raw_parts`] for more details.
264 /// This function is safe, but actually using the return value is unsafe.
265 /// See the documentation of [`from_raw_parts_mut`] for slice safety requirements.
267 /// [`slice_from_raw_parts`]: fn.slice_from_raw_parts.html
268 /// [`from_raw_parts_mut`]: ../../std/slice/fn.from_raw_parts_mut.html
270 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
271 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
272 pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
273 unsafe { Repr { raw: FatPtr { data, len } }.rust_mut }
276 /// Swaps the values at two mutable locations of the same type, without
277 /// deinitializing either.
279 /// But for the following two exceptions, this function is semantically
280 /// equivalent to [`mem::swap`]:
282 /// * It operates on raw pointers instead of references. When references are
283 /// available, [`mem::swap`] should be preferred.
285 /// * The two pointed-to values may overlap. If the values do overlap, then the
286 /// overlapping region of memory from `x` will be used. This is demonstrated
287 /// in the second example below.
289 /// [`mem::swap`]: ../mem/fn.swap.html
293 /// Behavior is undefined if any of the following conditions are violated:
295 /// * Both `x` and `y` must be [valid] for both reads and writes.
297 /// * Both `x` and `y` must be properly aligned.
299 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
301 /// [valid]: ../ptr/index.html#safety
305 /// Swapping two non-overlapping regions:
310 /// let mut array = [0, 1, 2, 3];
312 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
313 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
317 /// assert_eq!([2, 3, 0, 1], array);
321 /// Swapping two overlapping regions:
326 /// let mut array = [0, 1, 2, 3];
328 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
329 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
333 /// // The indices `1..3` of the slice overlap between `x` and `y`.
334 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
335 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
336 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
337 /// // This implementation is defined to make the latter choice.
338 /// assert_eq!([1, 0, 1, 2], array);
342 #[stable(feature = "rust1", since = "1.0.0")]
343 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
344 // Give ourselves some scratch space to work with.
345 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
346 let mut tmp = MaybeUninit::<T>::uninit();
349 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
350 copy(y, x, 1); // `x` and `y` may overlap
351 copy_nonoverlapping(tmp.as_ptr(), y, 1);
354 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
355 /// beginning at `x` and `y`. The two regions must *not* overlap.
359 /// Behavior is undefined if any of the following conditions are violated:
361 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
362 /// size_of::<T>()` bytes.
364 /// * Both `x` and `y` must be properly aligned.
366 /// * The region of memory beginning at `x` with a size of `count *
367 /// size_of::<T>()` bytes must *not* overlap with the region of memory
368 /// beginning at `y` with the same size.
370 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
371 /// the pointers must be non-NULL and properly aligned.
373 /// [valid]: ../ptr/index.html#safety
382 /// let mut x = [1, 2, 3, 4];
383 /// let mut y = [7, 8, 9];
386 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
389 /// assert_eq!(x, [7, 8, 3, 4]);
390 /// assert_eq!(y, [1, 2, 9]);
393 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
394 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
395 debug_assert!(is_aligned_and_not_null(x), "attempt to swap unaligned or null pointer");
396 debug_assert!(is_aligned_and_not_null(y), "attempt to swap unaligned or null pointer");
397 debug_assert!(is_nonoverlapping(x, y, count), "attempt to swap overlapping memory");
399 let x = x as *mut u8;
400 let y = y as *mut u8;
401 let len = mem::size_of::<T>() * count;
402 swap_nonoverlapping_bytes(x, y, len)
406 pub(crate) unsafe fn swap_nonoverlapping_one<T>(x: *mut T, y: *mut T) {
407 // For types smaller than the block optimization below,
408 // just swap directly to avoid pessimizing codegen.
409 if mem::size_of::<T>() < 32 {
411 copy_nonoverlapping(y, x, 1);
414 swap_nonoverlapping(x, y, 1);
419 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
420 // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
421 // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
422 // Haswell E processors. LLVM is more able to optimize if we give a struct a
423 // #[repr(simd)], even if we don't actually use this struct directly.
425 // FIXME repr(simd) broken on emscripten and redox
426 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))]
427 struct Block(u64, u64, u64, u64);
428 struct UnalignedBlock(u64, u64, u64, u64);
430 let block_size = mem::size_of::<Block>();
432 // Loop through x & y, copying them `Block` at a time
433 // The optimizer should unroll the loop fully for most types
434 // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
436 while i + block_size <= len {
437 // Create some uninitialized memory as scratch space
438 // Declaring `t` here avoids aligning the stack when this loop is unused
439 let mut t = mem::MaybeUninit::<Block>::uninit();
440 let t = t.as_mut_ptr() as *mut u8;
444 // Swap a block of bytes of x & y, using t as a temporary buffer
445 // This should be optimized into efficient SIMD operations where available
446 copy_nonoverlapping(x, t, block_size);
447 copy_nonoverlapping(y, x, block_size);
448 copy_nonoverlapping(t, y, block_size);
453 // Swap any remaining bytes
454 let mut t = mem::MaybeUninit::<UnalignedBlock>::uninit();
457 let t = t.as_mut_ptr() as *mut u8;
461 copy_nonoverlapping(x, t, rem);
462 copy_nonoverlapping(y, x, rem);
463 copy_nonoverlapping(t, y, rem);
467 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
469 /// Neither value is dropped.
471 /// This function is semantically equivalent to [`mem::replace`] except that it
472 /// operates on raw pointers instead of references. When references are
473 /// available, [`mem::replace`] should be preferred.
475 /// [`mem::replace`]: ../mem/fn.replace.html
479 /// Behavior is undefined if any of the following conditions are violated:
481 /// * `dst` must be [valid] for both reads and writes.
483 /// * `dst` must be properly aligned.
485 /// * `dst` must point to a properly initialized value of type `T`.
487 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
489 /// [valid]: ../ptr/index.html#safety
496 /// let mut rust = vec!['b', 'u', 's', 't'];
498 /// // `mem::replace` would have the same effect without requiring the unsafe
501 /// ptr::replace(&mut rust[0], 'r')
504 /// assert_eq!(b, 'b');
505 /// assert_eq!(rust, &['r', 'u', 's', 't']);
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
510 mem::swap(&mut *dst, &mut src); // cannot overlap
514 /// Reads the value from `src` without moving it. This leaves the
515 /// memory in `src` unchanged.
519 /// Behavior is undefined if any of the following conditions are violated:
521 /// * `src` must be [valid] for reads.
523 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
526 /// * `src` must point to a properly initialized value of type `T`.
528 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
536 /// let y = &x as *const i32;
539 /// assert_eq!(std::ptr::read(y), 12);
543 /// Manually implement [`mem::swap`]:
548 /// fn swap<T>(a: &mut T, b: &mut T) {
550 /// // Create a bitwise copy of the value at `a` in `tmp`.
551 /// let tmp = ptr::read(a);
553 /// // Exiting at this point (either by explicitly returning or by
554 /// // calling a function which panics) would cause the value in `tmp` to
555 /// // be dropped while the same value is still referenced by `a`. This
556 /// // could trigger undefined behavior if `T` is not `Copy`.
558 /// // Create a bitwise copy of the value at `b` in `a`.
559 /// // This is safe because mutable references cannot alias.
560 /// ptr::copy_nonoverlapping(b, a, 1);
562 /// // As above, exiting here could trigger undefined behavior because
563 /// // the same value is referenced by `a` and `b`.
565 /// // Move `tmp` into `b`.
566 /// ptr::write(b, tmp);
568 /// // `tmp` has been moved (`write` takes ownership of its second argument),
569 /// // so nothing is dropped implicitly here.
573 /// let mut foo = "foo".to_owned();
574 /// let mut bar = "bar".to_owned();
576 /// swap(&mut foo, &mut bar);
578 /// assert_eq!(foo, "bar");
579 /// assert_eq!(bar, "foo");
582 /// ## Ownership of the Returned Value
584 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
585 /// If `T` is not [`Copy`], using both the returned value and the value at
586 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
587 /// use because it will attempt to drop the value at `*src`.
589 /// [`write`] can be used to overwrite data without causing it to be dropped.
594 /// let mut s = String::from("foo");
596 /// // `s2` now points to the same underlying memory as `s`.
597 /// let mut s2: String = ptr::read(&s);
599 /// assert_eq!(s2, "foo");
601 /// // Assigning to `s2` causes its original value to be dropped. Beyond
602 /// // this point, `s` must no longer be used, as the underlying memory has
604 /// s2 = String::default();
605 /// assert_eq!(s2, "");
607 /// // Assigning to `s` would cause the old value to be dropped again,
608 /// // resulting in undefined behavior.
609 /// // s = String::from("bar"); // ERROR
611 /// // `ptr::write` can be used to overwrite a value without dropping it.
612 /// ptr::write(&mut s, String::from("bar"));
615 /// assert_eq!(s, "bar");
618 /// [`mem::swap`]: ../mem/fn.swap.html
619 /// [valid]: ../ptr/index.html#safety
620 /// [`Copy`]: ../marker/trait.Copy.html
621 /// [`read_unaligned`]: ./fn.read_unaligned.html
622 /// [`write`]: ./fn.write.html
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub unsafe fn read<T>(src: *const T) -> T {
626 // `copy_nonoverlapping` takes care of debug_assert.
627 let mut tmp = MaybeUninit::<T>::uninit();
628 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
632 /// Reads the value from `src` without moving it. This leaves the
633 /// memory in `src` unchanged.
635 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
639 /// Behavior is undefined if any of the following conditions are violated:
641 /// * `src` must be [valid] for reads.
643 /// * `src` must point to a properly initialized value of type `T`.
645 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
646 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
647 /// value and the value at `*src` can [violate memory safety][read-ownership].
649 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
651 /// [`Copy`]: ../marker/trait.Copy.html
652 /// [`read`]: ./fn.read.html
653 /// [`write_unaligned`]: ./fn.write_unaligned.html
654 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
655 /// [valid]: ../ptr/index.html#safety
657 /// ## On `packed` structs
659 /// It is currently impossible to create raw pointers to unaligned fields
660 /// of a packed struct.
662 /// Attempting to create a raw pointer to an `unaligned` struct field with
663 /// an expression such as `&packed.unaligned as *const FieldType` creates an
664 /// intermediate unaligned reference before converting that to a raw pointer.
665 /// That this reference is temporary and immediately cast is inconsequential
666 /// as the compiler always expects references to be properly aligned.
667 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
668 /// *undefined behavior* in your program.
670 /// An example of what not to do and how this relates to `read_unaligned` is:
673 /// #[repr(packed, C)]
679 /// let packed = Packed {
681 /// unaligned: 0x01020304,
685 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
687 /// // A temporary unaligned reference is created here which results in
688 /// // undefined behavior regardless of whether the reference is used or not.
689 /// &packed.unaligned
690 /// // Casting to a raw pointer doesn't help; the mistake already happened.
693 /// let v = std::ptr::read_unaligned(unaligned);
699 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
700 // FIXME: Update docs based on outcome of RFC #2582 and friends.
704 /// Read an usize value from a byte buffer:
709 /// fn read_usize(x: &[u8]) -> usize {
710 /// assert!(x.len() >= mem::size_of::<usize>());
712 /// let ptr = x.as_ptr() as *const usize;
714 /// unsafe { ptr.read_unaligned() }
718 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
719 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
720 // `copy_nonoverlapping` takes care of debug_assert.
721 let mut tmp = MaybeUninit::<T>::uninit();
722 copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::<T>());
726 /// Overwrites a memory location with the given value without reading or
727 /// dropping the old value.
729 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
730 /// allocations or resources, so care should be taken not to overwrite an object
731 /// that should be dropped.
733 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
734 /// location pointed to by `dst`.
736 /// This is appropriate for initializing uninitialized memory, or overwriting
737 /// memory that has previously been [`read`] from.
739 /// [`read`]: ./fn.read.html
743 /// Behavior is undefined if any of the following conditions are violated:
745 /// * `dst` must be [valid] for writes.
747 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
750 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
752 /// [valid]: ../ptr/index.html#safety
753 /// [`write_unaligned`]: ./fn.write_unaligned.html
761 /// let y = &mut x as *mut i32;
765 /// std::ptr::write(y, z);
766 /// assert_eq!(std::ptr::read(y), 12);
770 /// Manually implement [`mem::swap`]:
775 /// fn swap<T>(a: &mut T, b: &mut T) {
777 /// // Create a bitwise copy of the value at `a` in `tmp`.
778 /// let tmp = ptr::read(a);
780 /// // Exiting at this point (either by explicitly returning or by
781 /// // calling a function which panics) would cause the value in `tmp` to
782 /// // be dropped while the same value is still referenced by `a`. This
783 /// // could trigger undefined behavior if `T` is not `Copy`.
785 /// // Create a bitwise copy of the value at `b` in `a`.
786 /// // This is safe because mutable references cannot alias.
787 /// ptr::copy_nonoverlapping(b, a, 1);
789 /// // As above, exiting here could trigger undefined behavior because
790 /// // the same value is referenced by `a` and `b`.
792 /// // Move `tmp` into `b`.
793 /// ptr::write(b, tmp);
795 /// // `tmp` has been moved (`write` takes ownership of its second argument),
796 /// // so nothing is dropped implicitly here.
800 /// let mut foo = "foo".to_owned();
801 /// let mut bar = "bar".to_owned();
803 /// swap(&mut foo, &mut bar);
805 /// assert_eq!(foo, "bar");
806 /// assert_eq!(bar, "foo");
809 /// [`mem::swap`]: ../mem/fn.swap.html
811 #[stable(feature = "rust1", since = "1.0.0")]
812 pub unsafe fn write<T>(dst: *mut T, src: T) {
813 debug_assert!(is_aligned_and_not_null(dst), "attempt to write to unaligned or null pointer");
814 intrinsics::move_val_init(&mut *dst, src)
817 /// Overwrites a memory location with the given value without reading or
818 /// dropping the old value.
820 /// Unlike [`write`], the pointer may be unaligned.
822 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
823 /// could leak allocations or resources, so care should be taken not to overwrite
824 /// an object that should be dropped.
826 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
827 /// location pointed to by `dst`.
829 /// This is appropriate for initializing uninitialized memory, or overwriting
830 /// memory that has previously been read with [`read_unaligned`].
832 /// [`write`]: ./fn.write.html
833 /// [`read_unaligned`]: ./fn.read_unaligned.html
837 /// Behavior is undefined if any of the following conditions are violated:
839 /// * `dst` must be [valid] for writes.
841 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
843 /// [valid]: ../ptr/index.html#safety
845 /// ## On `packed` structs
847 /// It is currently impossible to create raw pointers to unaligned fields
848 /// of a packed struct.
850 /// Attempting to create a raw pointer to an `unaligned` struct field with
851 /// an expression such as `&packed.unaligned as *const FieldType` creates an
852 /// intermediate unaligned reference before converting that to a raw pointer.
853 /// That this reference is temporary and immediately cast is inconsequential
854 /// as the compiler always expects references to be properly aligned.
855 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
856 /// *undefined behavior* in your program.
858 /// An example of what not to do and how this relates to `write_unaligned` is:
861 /// #[repr(packed, C)]
867 /// let v = 0x01020304;
868 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
871 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
873 /// // A temporary unaligned reference is created here which results in
874 /// // undefined behavior regardless of whether the reference is used or not.
875 /// &mut packed.unaligned
876 /// // Casting to a raw pointer doesn't help; the mistake already happened.
879 /// std::ptr::write_unaligned(unaligned, v);
885 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
886 // FIXME: Update docs based on outcome of RFC #2582 and friends.
890 /// Write an usize value to a byte buffer:
895 /// fn write_usize(x: &mut [u8], val: usize) {
896 /// assert!(x.len() >= mem::size_of::<usize>());
898 /// let ptr = x.as_mut_ptr() as *mut usize;
900 /// unsafe { ptr.write_unaligned(val) }
904 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
905 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
906 // `copy_nonoverlapping` takes care of debug_assert.
907 copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::<T>());
911 /// Performs a volatile read of the value from `src` without moving it. This
912 /// leaves the memory in `src` unchanged.
914 /// Volatile operations are intended to act on I/O memory, and are guaranteed
915 /// to not be elided or reordered by the compiler across other volatile
918 /// [`write_volatile`]: ./fn.write_volatile.html
922 /// Rust does not currently have a rigorously and formally defined memory model,
923 /// so the precise semantics of what "volatile" means here is subject to change
924 /// over time. That being said, the semantics will almost always end up pretty
925 /// similar to [C11's definition of volatile][c11].
927 /// The compiler shouldn't change the relative order or number of volatile
928 /// memory operations. However, volatile memory operations on zero-sized types
929 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
930 /// and may be ignored.
932 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
936 /// Behavior is undefined if any of the following conditions are violated:
938 /// * `src` must be [valid] for reads.
940 /// * `src` must be properly aligned.
942 /// * `src` must point to a properly initialized value of type `T`.
944 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
945 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
946 /// value and the value at `*src` can [violate memory safety][read-ownership].
947 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
950 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
952 /// [valid]: ../ptr/index.html#safety
953 /// [`Copy`]: ../marker/trait.Copy.html
954 /// [`read`]: ./fn.read.html
955 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
957 /// Just like in C, whether an operation is volatile has no bearing whatsoever
958 /// on questions involving concurrent access from multiple threads. Volatile
959 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
960 /// a race between a `read_volatile` and any write operation to the same location
961 /// is undefined behavior.
969 /// let y = &x as *const i32;
972 /// assert_eq!(std::ptr::read_volatile(y), 12);
976 #[stable(feature = "volatile", since = "1.9.0")]
977 pub unsafe fn read_volatile<T>(src: *const T) -> T {
978 debug_assert!(is_aligned_and_not_null(src), "attempt to read from unaligned or null pointer");
979 intrinsics::volatile_load(src)
982 /// Performs a volatile write of a memory location with the given value without
983 /// reading or dropping the old value.
985 /// Volatile operations are intended to act on I/O memory, and are guaranteed
986 /// to not be elided or reordered by the compiler across other volatile
989 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
990 /// could leak allocations or resources, so care should be taken not to overwrite
991 /// an object that should be dropped.
993 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
994 /// location pointed to by `dst`.
996 /// [`read_volatile`]: ./fn.read_volatile.html
1000 /// Rust does not currently have a rigorously and formally defined memory model,
1001 /// so the precise semantics of what "volatile" means here is subject to change
1002 /// over time. That being said, the semantics will almost always end up pretty
1003 /// similar to [C11's definition of volatile][c11].
1005 /// The compiler shouldn't change the relative order or number of volatile
1006 /// memory operations. However, volatile memory operations on zero-sized types
1007 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
1008 /// and may be ignored.
1010 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1014 /// Behavior is undefined if any of the following conditions are violated:
1016 /// * `dst` must be [valid] for writes.
1018 /// * `dst` must be properly aligned.
1020 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
1022 /// [valid]: ../ptr/index.html#safety
1024 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1025 /// on questions involving concurrent access from multiple threads. Volatile
1026 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1027 /// a race between a `write_volatile` and any other operation (reading or writing)
1028 /// on the same location is undefined behavior.
1036 /// let y = &mut x as *mut i32;
1040 /// std::ptr::write_volatile(y, z);
1041 /// assert_eq!(std::ptr::read_volatile(y), 12);
1045 #[stable(feature = "volatile", since = "1.9.0")]
1046 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
1047 debug_assert!(is_aligned_and_not_null(dst), "attempt to write to unaligned or null pointer");
1048 intrinsics::volatile_store(dst, src);
1051 /// Align pointer `p`.
1053 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
1054 /// to pointer `p` so that pointer `p` would get aligned to `a`.
1056 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
1057 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
1060 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
1061 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
1062 /// than trying to adapt this to accommodate that change.
1064 /// Any questions go to @nagisa.
1065 #[lang = "align_offset"]
1066 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
1067 /// Calculate multiplicative modular inverse of `x` modulo `m`.
1069 /// This implementation is tailored for align_offset and has following preconditions:
1071 /// * `m` is a power-of-two;
1072 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1074 /// Implementation of this function shall not panic. Ever.
1076 fn mod_inv(x: usize, m: usize) -> usize {
1077 /// Multiplicative modular inverse table modulo 2⁴ = 16.
1079 /// Note, that this table does not contain values where inverse does not exist (i.e., for
1080 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
1081 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
1082 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
1083 const INV_TABLE_MOD: usize = 16;
1085 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
1087 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
1088 if m <= INV_TABLE_MOD {
1089 table_inverse & (m - 1)
1091 // We iterate "up" using the following formula:
1093 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1095 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
1096 let mut inverse = table_inverse;
1097 let mut going_mod = INV_TABLE_MOD_SQUARED;
1099 // y = y * (2 - xy) mod n
1101 // Note, that we use wrapping operations here intentionally – the original formula
1102 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
1103 // usize::max_value()` instead, because we take the result `mod n` at the end
1105 inverse = inverse.wrapping_mul(2usize.wrapping_sub(x.wrapping_mul(inverse)));
1107 return inverse & (m - 1);
1109 going_mod = going_mod.wrapping_mul(going_mod);
1114 let stride = mem::size_of::<T>();
1115 let a_minus_one = a.wrapping_sub(1);
1116 let pmoda = p as usize & a_minus_one;
1119 // Already aligned. Yay!
1124 return if stride == 0 {
1125 // If the pointer is not aligned, and the element is zero-sized, then no amount of
1126 // elements will ever align the pointer.
1129 a.wrapping_sub(pmoda)
1133 let smoda = stride & a_minus_one;
1134 // a is power-of-two so cannot be 0. stride = 0 is handled above.
1135 let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
1136 let gcd = 1usize << gcdpow;
1138 if p as usize & (gcd.wrapping_sub(1)) == 0 {
1139 // This branch solves for the following linear congruence equation:
1141 // ` p + so = 0 mod a `
1143 // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1144 // requested alignment.
1146 // With `g = gcd(a, s)`, and the above asserting that `p` is also divisible by `g`, we can
1147 // denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1149 // ` p' + s'o = 0 mod a' `
1150 // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1152 // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the second
1153 // term is "how does incrementing `p` by `s` bytes change the relative alignment of `p`" (again
1155 // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1158 // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1159 // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`.
1160 let a2 = a >> gcdpow;
1161 let a2minus1 = a2.wrapping_sub(1);
1162 let s2 = smoda >> gcdpow;
1163 let minusp2 = a2.wrapping_sub(pmoda >> gcdpow);
1164 return (minusp2.wrapping_mul(mod_inv(s2, a2))) & a2minus1;
1167 // Cannot be aligned at all.
1171 /// Compares raw pointers for equality.
1173 /// This is the same as using the `==` operator, but less generic:
1174 /// the arguments have to be `*const T` raw pointers,
1175 /// not anything that implements `PartialEq`.
1177 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
1178 /// by their address rather than comparing the values they point to
1179 /// (which is what the `PartialEq for &T` implementation does).
1187 /// let other_five = 5;
1188 /// let five_ref = &five;
1189 /// let same_five_ref = &five;
1190 /// let other_five_ref = &other_five;
1192 /// assert!(five_ref == same_five_ref);
1193 /// assert!(ptr::eq(five_ref, same_five_ref));
1195 /// assert!(five_ref == other_five_ref);
1196 /// assert!(!ptr::eq(five_ref, other_five_ref));
1199 /// Slices are also compared by their length (fat pointers):
1202 /// let a = [1, 2, 3];
1203 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
1204 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
1205 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
1208 /// Traits are also compared by their implementation:
1211 /// #[repr(transparent)]
1212 /// struct Wrapper { member: i32 }
1215 /// impl Trait for Wrapper {}
1216 /// impl Trait for i32 {}
1218 /// let wrapper = Wrapper { member: 10 };
1220 /// // Pointers have equal addresses.
1221 /// assert!(std::ptr::eq(
1222 /// &wrapper as *const Wrapper as *const u8,
1223 /// &wrapper.member as *const i32 as *const u8
1226 /// // Objects have equal addresses, but `Trait` has different implementations.
1227 /// assert!(!std::ptr::eq(
1228 /// &wrapper as &dyn Trait,
1229 /// &wrapper.member as &dyn Trait,
1231 /// assert!(!std::ptr::eq(
1232 /// &wrapper as &dyn Trait as *const dyn Trait,
1233 /// &wrapper.member as &dyn Trait as *const dyn Trait,
1236 /// // Converting the reference to a `*const u8` compares by address.
1237 /// assert!(std::ptr::eq(
1238 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
1239 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
1242 #[stable(feature = "ptr_eq", since = "1.17.0")]
1244 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
1248 /// Hash a raw pointer.
1250 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
1251 /// by its address rather than the value it points to
1252 /// (which is what the `Hash for &T` implementation does).
1257 /// use std::collections::hash_map::DefaultHasher;
1258 /// use std::hash::{Hash, Hasher};
1262 /// let five_ref = &five;
1264 /// let mut hasher = DefaultHasher::new();
1265 /// ptr::hash(five_ref, &mut hasher);
1266 /// let actual = hasher.finish();
1268 /// let mut hasher = DefaultHasher::new();
1269 /// (five_ref as *const i32).hash(&mut hasher);
1270 /// let expected = hasher.finish();
1272 /// assert_eq!(actual, expected);
1274 #[stable(feature = "ptr_hash", since = "1.35.0")]
1275 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
1276 use crate::hash::Hash;
1280 // Impls for function pointers
1281 macro_rules! fnptr_impls_safety_abi {
1282 ($FnTy: ty, $($Arg: ident),*) => {
1283 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1284 impl<Ret, $($Arg),*> PartialEq for $FnTy {
1286 fn eq(&self, other: &Self) -> bool {
1287 *self as usize == *other as usize
1291 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1292 impl<Ret, $($Arg),*> Eq for $FnTy {}
1294 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1295 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
1297 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1298 (*self as usize).partial_cmp(&(*other as usize))
1302 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1303 impl<Ret, $($Arg),*> Ord for $FnTy {
1305 fn cmp(&self, other: &Self) -> Ordering {
1306 (*self as usize).cmp(&(*other as usize))
1310 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1311 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
1312 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
1313 state.write_usize(*self as usize)
1317 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1318 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
1319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1320 fmt::Pointer::fmt(&(*self as *const ()), f)
1324 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1325 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
1326 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1327 fmt::Pointer::fmt(&(*self as *const ()), f)
1333 macro_rules! fnptr_impls_args {
1334 ($($Arg: ident),+) => {
1335 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1336 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1337 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1338 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1339 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1340 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1343 // No variadic functions with 0 parameters
1344 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
1345 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
1346 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
1347 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
1351 fnptr_impls_args! {}
1352 fnptr_impls_args! { A }
1353 fnptr_impls_args! { A, B }
1354 fnptr_impls_args! { A, B, C }
1355 fnptr_impls_args! { A, B, C, D }
1356 fnptr_impls_args! { A, B, C, D, E }
1357 fnptr_impls_args! { A, B, C, D, E, F }
1358 fnptr_impls_args! { A, B, C, D, E, F, G }
1359 fnptr_impls_args! { A, B, C, D, E, F, G, H }
1360 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
1361 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
1362 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
1363 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }