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 //! * All accesses performed by functions in this module are *non-atomic* in the sense
22 //! of [atomic operations] used to synchronize between threads. This means it is
23 //! undefined behavior to perform two concurrent accesses to the same location from different
24 //! threads unless both accesses only read from memory. Notice that this explicitly
25 //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
26 //! be used for inter-thread synchronization.
27 //! * The result of casting a reference to a pointer is valid for as long as the
28 //! underlying object is live and no reference (just raw pointers) is used to
29 //! access the same memory.
31 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
32 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
33 //! will be provided eventually, as the [aliasing] rules are being determined. For more
34 //! information, see the [book] as well as the section in the reference devoted
35 //! to [undefined behavior][ub].
39 //! Valid raw pointers as defined above are not necessarily properly aligned (where
40 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
41 //! aligned to `mem::align_of::<T>()`). However, most functions require their
42 //! arguments to be properly aligned, and will explicitly state
43 //! this requirement in their documentation. Notable exceptions to this are
44 //! [`read_unaligned`] and [`write_unaligned`].
46 //! When a function requires proper alignment, it does so even if the access
47 //! has size 0, i.e., even if memory is not actually touched. Consider using
48 //! [`NonNull::dangling`] in such cases.
50 //! [aliasing]: ../../nomicon/aliasing.html
51 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
52 //! [ub]: ../../reference/behavior-considered-undefined.html
53 //! [null]: ./fn.null.html
54 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
55 //! [atomic operations]: ../../std/sync/atomic/index.html
56 //! [`copy`]: ../../std/ptr/fn.copy.html
57 //! [`offset`]: ../../std/primitive.pointer.html#method.offset
58 //! [`read_unaligned`]: ./fn.read_unaligned.html
59 //! [`write_unaligned`]: ./fn.write_unaligned.html
60 //! [`read_volatile`]: ./fn.read_volatile.html
61 //! [`write_volatile`]: ./fn.write_volatile.html
62 //! [`NonNull::dangling`]: ./struct.NonNull.html#method.dangling
64 #![stable(feature = "rust1", since = "1.0.0")]
66 use crate::intrinsics;
69 use crate::mem::{self, MaybeUninit};
70 use crate::cmp::Ordering::{self, Less, Equal, Greater};
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub use crate::intrinsics::copy_nonoverlapping;
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub use crate::intrinsics::copy;
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use crate::intrinsics::write_bytes;
82 #[stable(feature = "nonnull", since = "1.25.0")]
83 pub use non_null::NonNull;
86 #[unstable(feature = "ptr_internals", issue = "0")]
87 pub use unique::Unique;
89 /// Executes the destructor (if any) of the pointed-to value.
91 /// This is semantically equivalent to calling [`ptr::read`] and discarding
92 /// the result, but has the following advantages:
94 /// * It is *required* to use `drop_in_place` to drop unsized types like
95 /// trait objects, because they can't be read out onto the stack and
98 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
99 /// dropping manually allocated memory (e.g., when writing Box/Rc/Vec),
100 /// as the compiler doesn't need to prove that it's sound to elide the
103 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
104 /// location first using [`ptr::read_unaligned`].
106 /// [`ptr::read`]: ../ptr/fn.read.html
107 /// [`ptr::read_unaligned`]: ../ptr/fn.read_unaligned.html
111 /// Behavior is undefined if any of the following conditions are violated:
113 /// * `to_drop` must be [valid] for reads.
115 /// * `to_drop` must be properly aligned.
117 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
118 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
119 /// foo` counts as a use because it will cause the value to be dropped
120 /// again. [`write`] can be used to overwrite data without causing it to be
123 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
125 /// [valid]: ../ptr/index.html#safety
126 /// [`Copy`]: ../marker/trait.Copy.html
127 /// [`write`]: ../ptr/fn.write.html
131 /// Manually remove the last item from a vector:
137 /// let last = Rc::new(1);
138 /// let weak = Rc::downgrade(&last);
140 /// let mut v = vec![Rc::new(0), last];
143 /// // Get a raw pointer to the last element in `v`.
144 /// let ptr = &mut v[1] as *mut _;
145 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
146 /// // to prevent issues if the `drop_in_place` below panics.
148 /// // Without a call `drop_in_place`, the last item would never be dropped,
149 /// // and the memory it manages would be leaked.
150 /// ptr::drop_in_place(ptr);
153 /// assert_eq!(v, &[0.into()]);
155 /// // Ensure that the last item was dropped.
156 /// assert!(weak.upgrade().is_none());
159 /// Notice that the compiler performs this copy automatically when dropping packed structs,
160 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
162 #[stable(feature = "drop_in_place", since = "1.8.0")]
164 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
165 real_drop_in_place(&mut *to_drop)
168 // The real `drop_in_place` -- the one that gets called implicitly when variables go
169 // out of scope -- should have a safe reference and not a raw pointer as argument
170 // type. When we drop a local variable, we access it with a pointer that behaves
171 // like a safe reference; transmuting that to a raw pointer does not mean we can
172 // actually access it with raw pointers.
173 #[lang = "drop_in_place"]
174 #[allow(unconditional_recursion)]
175 unsafe fn real_drop_in_place<T: ?Sized>(to_drop: &mut T) {
176 // Code here does not matter - this is replaced by the
177 // real drop glue by the compiler.
178 real_drop_in_place(to_drop)
181 /// Creates a null raw pointer.
188 /// let p: *const i32 = ptr::null();
189 /// assert!(p.is_null());
192 #[stable(feature = "rust1", since = "1.0.0")]
194 pub const fn null<T>() -> *const T { 0 as *const T }
196 /// Creates a null mutable raw pointer.
203 /// let p: *mut i32 = ptr::null_mut();
204 /// assert!(p.is_null());
207 #[stable(feature = "rust1", since = "1.0.0")]
209 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
212 pub(crate) union Repr<T> {
213 pub(crate) rust: *const [T],
215 pub(crate) raw: FatPtr<T>,
219 pub(crate) struct FatPtr<T> {
221 pub(crate) len: usize,
224 /// Forms a slice from a pointer and a length.
226 /// The `len` argument is the number of **elements**, not the number of bytes.
231 /// #![feature(slice_from_raw_parts)]
234 /// // create a slice pointer when starting out with a pointer to the first element
235 /// let mut x = [5, 6, 7];
236 /// let ptr = &mut x[0] as *mut _;
237 /// let slice = ptr::slice_from_raw_parts_mut(ptr, 3);
238 /// assert_eq!(unsafe { &*slice }[2], 7);
241 #[unstable(feature = "slice_from_raw_parts", reason = "recently added", issue = "36925")]
242 pub fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
243 unsafe { Repr { raw: FatPtr { data, len } }.rust }
246 /// Performs the same functionality as [`from_raw_parts`], except that a
247 /// mutable slice is returned.
249 /// See the documentation of [`from_raw_parts`] for more details.
251 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
253 #[unstable(feature = "slice_from_raw_parts", reason = "recently added", issue = "36925")]
254 pub fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
255 unsafe { Repr { raw: FatPtr { data, len } }.rust_mut }
258 /// Swaps the values at two mutable locations of the same type, without
259 /// deinitializing either.
261 /// But for the following two exceptions, this function is semantically
262 /// equivalent to [`mem::swap`]:
264 /// * It operates on raw pointers instead of references. When references are
265 /// available, [`mem::swap`] should be preferred.
267 /// * The two pointed-to values may overlap. If the values do overlap, then the
268 /// overlapping region of memory from `x` will be used. This is demonstrated
269 /// in the second example below.
271 /// [`mem::swap`]: ../mem/fn.swap.html
275 /// Behavior is undefined if any of the following conditions are violated:
277 /// * Both `x` and `y` must be [valid] for reads and writes.
279 /// * Both `x` and `y` must be properly aligned.
281 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
283 /// [valid]: ../ptr/index.html#safety
287 /// Swapping two non-overlapping regions:
292 /// let mut array = [0, 1, 2, 3];
294 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
295 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
299 /// assert_eq!([2, 3, 0, 1], array);
303 /// Swapping two overlapping regions:
308 /// let mut array = [0, 1, 2, 3];
310 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
311 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
315 /// // The indices `1..3` of the slice overlap between `x` and `y`.
316 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
317 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
318 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
319 /// // This implementation is defined to make the latter choice.
320 /// assert_eq!([1, 0, 1, 2], array);
324 #[stable(feature = "rust1", since = "1.0.0")]
325 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
326 // Give ourselves some scratch space to work with.
327 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
328 let mut tmp = MaybeUninit::<T>::uninit();
331 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
332 copy(y, x, 1); // `x` and `y` may overlap
333 copy_nonoverlapping(tmp.as_ptr(), y, 1);
336 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
337 /// beginning at `x` and `y`. The two regions must *not* overlap.
341 /// Behavior is undefined if any of the following conditions are violated:
343 /// * Both `x` and `y` must be [valid] for reads and writes of `count *
344 /// size_of::<T>()` bytes.
346 /// * Both `x` and `y` must be properly aligned.
348 /// * The region of memory beginning at `x` with a size of `count *
349 /// size_of::<T>()` bytes must *not* overlap with the region of memory
350 /// beginning at `y` with the same size.
352 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
353 /// the pointers must be non-NULL and properly aligned.
355 /// [valid]: ../ptr/index.html#safety
364 /// let mut x = [1, 2, 3, 4];
365 /// let mut y = [7, 8, 9];
368 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
371 /// assert_eq!(x, [7, 8, 3, 4]);
372 /// assert_eq!(y, [1, 2, 9]);
375 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
376 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
377 let x = x as *mut u8;
378 let y = y as *mut u8;
379 let len = mem::size_of::<T>() * count;
380 swap_nonoverlapping_bytes(x, y, len)
384 pub(crate) unsafe fn swap_nonoverlapping_one<T>(x: *mut T, y: *mut T) {
385 // For types smaller than the block optimization below,
386 // just swap directly to avoid pessimizing codegen.
387 if mem::size_of::<T>() < 32 {
389 copy_nonoverlapping(y, x, 1);
392 swap_nonoverlapping(x, y, 1);
397 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
398 // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
399 // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
400 // Haswell E processors. LLVM is more able to optimize if we give a struct a
401 // #[repr(simd)], even if we don't actually use this struct directly.
403 // FIXME repr(simd) broken on emscripten and redox
404 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))]
405 struct Block(u64, u64, u64, u64);
406 struct UnalignedBlock(u64, u64, u64, u64);
408 let block_size = mem::size_of::<Block>();
410 // Loop through x & y, copying them `Block` at a time
411 // The optimizer should unroll the loop fully for most types
412 // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
414 while i + block_size <= len {
415 // Create some uninitialized memory as scratch space
416 // Declaring `t` here avoids aligning the stack when this loop is unused
417 let mut t = mem::MaybeUninit::<Block>::uninit();
418 let t = t.as_mut_ptr() as *mut u8;
422 // Swap a block of bytes of x & y, using t as a temporary buffer
423 // This should be optimized into efficient SIMD operations where available
424 copy_nonoverlapping(x, t, block_size);
425 copy_nonoverlapping(y, x, block_size);
426 copy_nonoverlapping(t, y, block_size);
431 // Swap any remaining bytes
432 let mut t = mem::MaybeUninit::<UnalignedBlock>::uninit();
435 let t = t.as_mut_ptr() as *mut u8;
439 copy_nonoverlapping(x, t, rem);
440 copy_nonoverlapping(y, x, rem);
441 copy_nonoverlapping(t, y, rem);
445 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
447 /// Neither value is dropped.
449 /// This function is semantically equivalent to [`mem::replace`] except that it
450 /// operates on raw pointers instead of references. When references are
451 /// available, [`mem::replace`] should be preferred.
453 /// [`mem::replace`]: ../mem/fn.replace.html
457 /// Behavior is undefined if any of the following conditions are violated:
459 /// * `dst` must be [valid] for writes.
461 /// * `dst` must be properly aligned.
463 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
465 /// [valid]: ../ptr/index.html#safety
472 /// let mut rust = vec!['b', 'u', 's', 't'];
474 /// // `mem::replace` would have the same effect without requiring the unsafe
477 /// ptr::replace(&mut rust[0], 'r')
480 /// assert_eq!(b, 'b');
481 /// assert_eq!(rust, &['r', 'u', 's', 't']);
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
486 mem::swap(&mut *dst, &mut src); // cannot overlap
490 /// Reads the value from `src` without moving it. This leaves the
491 /// memory in `src` unchanged.
495 /// Behavior is undefined if any of the following conditions are violated:
497 /// * `src` must be [valid] for reads.
499 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
502 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
510 /// let y = &x as *const i32;
513 /// assert_eq!(std::ptr::read(y), 12);
517 /// Manually implement [`mem::swap`]:
522 /// fn swap<T>(a: &mut T, b: &mut T) {
524 /// // Create a bitwise copy of the value at `a` in `tmp`.
525 /// let tmp = ptr::read(a);
527 /// // Exiting at this point (either by explicitly returning or by
528 /// // calling a function which panics) would cause the value in `tmp` to
529 /// // be dropped while the same value is still referenced by `a`. This
530 /// // could trigger undefined behavior if `T` is not `Copy`.
532 /// // Create a bitwise copy of the value at `b` in `a`.
533 /// // This is safe because mutable references cannot alias.
534 /// ptr::copy_nonoverlapping(b, a, 1);
536 /// // As above, exiting here could trigger undefined behavior because
537 /// // the same value is referenced by `a` and `b`.
539 /// // Move `tmp` into `b`.
540 /// ptr::write(b, tmp);
542 /// // `tmp` has been moved (`write` takes ownership of its second argument),
543 /// // so nothing is dropped implicitly here.
547 /// let mut foo = "foo".to_owned();
548 /// let mut bar = "bar".to_owned();
550 /// swap(&mut foo, &mut bar);
552 /// assert_eq!(foo, "bar");
553 /// assert_eq!(bar, "foo");
556 /// ## Ownership of the Returned Value
558 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
559 /// If `T` is not [`Copy`], using both the returned value and the value at
560 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
561 /// use because it will attempt to drop the value at `*src`.
563 /// [`write`] can be used to overwrite data without causing it to be dropped.
568 /// let mut s = String::from("foo");
570 /// // `s2` now points to the same underlying memory as `s`.
571 /// let mut s2: String = ptr::read(&s);
573 /// assert_eq!(s2, "foo");
575 /// // Assigning to `s2` causes its original value to be dropped. Beyond
576 /// // this point, `s` must no longer be used, as the underlying memory has
578 /// s2 = String::default();
579 /// assert_eq!(s2, "");
581 /// // Assigning to `s` would cause the old value to be dropped again,
582 /// // resulting in undefined behavior.
583 /// // s = String::from("bar"); // ERROR
585 /// // `ptr::write` can be used to overwrite a value without dropping it.
586 /// ptr::write(&mut s, String::from("bar"));
589 /// assert_eq!(s, "bar");
592 /// [`mem::swap`]: ../mem/fn.swap.html
593 /// [valid]: ../ptr/index.html#safety
594 /// [`Copy`]: ../marker/trait.Copy.html
595 /// [`read_unaligned`]: ./fn.read_unaligned.html
596 /// [`write`]: ./fn.write.html
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub unsafe fn read<T>(src: *const T) -> T {
600 let mut tmp = MaybeUninit::<T>::uninit();
601 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
605 /// Reads the value from `src` without moving it. This leaves the
606 /// memory in `src` unchanged.
608 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
612 /// Behavior is undefined if any of the following conditions are violated:
614 /// * `src` must be [valid] for reads.
616 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
617 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
618 /// value and the value at `*src` can [violate memory safety][read-ownership].
620 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
622 /// [`Copy`]: ../marker/trait.Copy.html
623 /// [`read`]: ./fn.read.html
624 /// [`write_unaligned`]: ./fn.write_unaligned.html
625 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
626 /// [valid]: ../ptr/index.html#safety
628 /// ## On `packed` structs
630 /// It is currently impossible to create raw pointers to unaligned fields
631 /// of a packed struct.
633 /// Attempting to create a raw pointer to an `unaligned` struct field with
634 /// an expression such as `&packed.unaligned as *const FieldType` creates an
635 /// intermediate unaligned reference before converting that to a raw pointer.
636 /// That this reference is temporary and immediately cast is inconsequential
637 /// as the compiler always expects references to be properly aligned.
638 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
639 /// *undefined behavior* in your program.
641 /// An example of what not to do and how this relates to `read_unaligned` is:
644 /// #[repr(packed, C)]
650 /// let packed = Packed {
652 /// unaligned: 0x01020304,
656 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
658 /// // A temporary unaligned reference is created here which results in
659 /// // undefined behavior regardless of whether the reference is used or not.
660 /// &packed.unaligned
661 /// // Casting to a raw pointer doesn't help; the mistake already happened.
664 /// let v = std::ptr::read_unaligned(unaligned);
670 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
671 // FIXME: Update docs based on outcome of RFC #2582 and friends.
675 /// Read an usize value from a byte buffer:
680 /// fn read_usize(x: &[u8]) -> usize {
681 /// assert!(x.len() >= mem::size_of::<usize>());
683 /// let ptr = x.as_ptr() as *const usize;
685 /// unsafe { ptr.read_unaligned() }
689 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
690 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
691 let mut tmp = MaybeUninit::<T>::uninit();
692 copy_nonoverlapping(src as *const u8,
693 tmp.as_mut_ptr() as *mut u8,
694 mem::size_of::<T>());
698 /// Overwrites a memory location with the given value without reading or
699 /// dropping the old value.
701 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
702 /// allocations or resources, so care should be taken not to overwrite an object
703 /// that should be dropped.
705 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
706 /// location pointed to by `dst`.
708 /// This is appropriate for initializing uninitialized memory, or overwriting
709 /// memory that has previously been [`read`] from.
711 /// [`read`]: ./fn.read.html
715 /// Behavior is undefined if any of the following conditions are violated:
717 /// * `dst` must be [valid] for writes.
719 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
722 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
724 /// [valid]: ../ptr/index.html#safety
725 /// [`write_unaligned`]: ./fn.write_unaligned.html
733 /// let y = &mut x as *mut i32;
737 /// std::ptr::write(y, z);
738 /// assert_eq!(std::ptr::read(y), 12);
742 /// Manually implement [`mem::swap`]:
747 /// fn swap<T>(a: &mut T, b: &mut T) {
749 /// // Create a bitwise copy of the value at `a` in `tmp`.
750 /// let tmp = ptr::read(a);
752 /// // Exiting at this point (either by explicitly returning or by
753 /// // calling a function which panics) would cause the value in `tmp` to
754 /// // be dropped while the same value is still referenced by `a`. This
755 /// // could trigger undefined behavior if `T` is not `Copy`.
757 /// // Create a bitwise copy of the value at `b` in `a`.
758 /// // This is safe because mutable references cannot alias.
759 /// ptr::copy_nonoverlapping(b, a, 1);
761 /// // As above, exiting here could trigger undefined behavior because
762 /// // the same value is referenced by `a` and `b`.
764 /// // Move `tmp` into `b`.
765 /// ptr::write(b, tmp);
767 /// // `tmp` has been moved (`write` takes ownership of its second argument),
768 /// // so nothing is dropped implicitly here.
772 /// let mut foo = "foo".to_owned();
773 /// let mut bar = "bar".to_owned();
775 /// swap(&mut foo, &mut bar);
777 /// assert_eq!(foo, "bar");
778 /// assert_eq!(bar, "foo");
781 /// [`mem::swap`]: ../mem/fn.swap.html
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub unsafe fn write<T>(dst: *mut T, src: T) {
785 intrinsics::move_val_init(&mut *dst, src)
788 /// Overwrites a memory location with the given value without reading or
789 /// dropping the old value.
791 /// Unlike [`write`], the pointer may be unaligned.
793 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
794 /// could leak allocations or resources, so care should be taken not to overwrite
795 /// an object that should be dropped.
797 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
798 /// location pointed to by `dst`.
800 /// This is appropriate for initializing uninitialized memory, or overwriting
801 /// memory that has previously been read with [`read_unaligned`].
803 /// [`write`]: ./fn.write.html
804 /// [`read_unaligned`]: ./fn.read_unaligned.html
808 /// Behavior is undefined if any of the following conditions are violated:
810 /// * `dst` must be [valid] for writes.
812 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
814 /// [valid]: ../ptr/index.html#safety
816 /// ## On `packed` structs
818 /// It is currently impossible to create raw pointers to unaligned fields
819 /// of a packed struct.
821 /// Attempting to create a raw pointer to an `unaligned` struct field with
822 /// an expression such as `&packed.unaligned as *const FieldType` creates an
823 /// intermediate unaligned reference before converting that to a raw pointer.
824 /// That this reference is temporary and immediately cast is inconsequential
825 /// as the compiler always expects references to be properly aligned.
826 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
827 /// *undefined behavior* in your program.
829 /// An example of what not to do and how this relates to `write_unaligned` is:
832 /// #[repr(packed, C)]
838 /// let v = 0x01020304;
839 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
842 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
844 /// // A temporary unaligned reference is created here which results in
845 /// // undefined behavior regardless of whether the reference is used or not.
846 /// &mut packed.unaligned
847 /// // Casting to a raw pointer doesn't help; the mistake already happened.
850 /// std::ptr::write_unaligned(unaligned, v);
856 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
857 // FIXME: Update docs based on outcome of RFC #2582 and friends.
861 /// Write an usize value to a byte buffer:
866 /// fn write_usize(x: &mut [u8], val: usize) {
867 /// assert!(x.len() >= mem::size_of::<usize>());
869 /// let ptr = x.as_mut_ptr() as *mut usize;
871 /// unsafe { ptr.write_unaligned(val) }
875 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
876 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
877 copy_nonoverlapping(&src as *const T as *const u8,
879 mem::size_of::<T>());
883 /// Performs a volatile read of the value from `src` without moving it. This
884 /// leaves the memory in `src` unchanged.
886 /// Volatile operations are intended to act on I/O memory, and are guaranteed
887 /// to not be elided or reordered by the compiler across other volatile
890 /// [`write_volatile`]: ./fn.write_volatile.html
894 /// Rust does not currently have a rigorously and formally defined memory model,
895 /// so the precise semantics of what "volatile" means here is subject to change
896 /// over time. That being said, the semantics will almost always end up pretty
897 /// similar to [C11's definition of volatile][c11].
899 /// The compiler shouldn't change the relative order or number of volatile
900 /// memory operations. However, volatile memory operations on zero-sized types
901 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
902 /// and may be ignored.
904 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
908 /// Behavior is undefined if any of the following conditions are violated:
910 /// * `src` must be [valid] for reads.
912 /// * `src` must be properly aligned.
914 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
915 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
916 /// value and the value at `*src` can [violate memory safety][read-ownership].
917 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
920 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
922 /// [valid]: ../ptr/index.html#safety
923 /// [`Copy`]: ../marker/trait.Copy.html
924 /// [`read`]: ./fn.read.html
925 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
927 /// Just like in C, whether an operation is volatile has no bearing whatsoever
928 /// on questions involving concurrent access from multiple threads. Volatile
929 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
930 /// a race between a `read_volatile` and any write operation to the same location
931 /// is undefined behavior.
939 /// let y = &x as *const i32;
942 /// assert_eq!(std::ptr::read_volatile(y), 12);
946 #[stable(feature = "volatile", since = "1.9.0")]
947 pub unsafe fn read_volatile<T>(src: *const T) -> T {
948 intrinsics::volatile_load(src)
951 /// Performs a volatile write of a memory location with the given value without
952 /// reading or dropping the old value.
954 /// Volatile operations are intended to act on I/O memory, and are guaranteed
955 /// to not be elided or reordered by the compiler across other volatile
958 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
959 /// could leak allocations or resources, so care should be taken not to overwrite
960 /// an object that should be dropped.
962 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
963 /// location pointed to by `dst`.
965 /// [`read_volatile`]: ./fn.read_volatile.html
969 /// Rust does not currently have a rigorously and formally defined memory model,
970 /// so the precise semantics of what "volatile" means here is subject to change
971 /// over time. That being said, the semantics will almost always end up pretty
972 /// similar to [C11's definition of volatile][c11].
974 /// The compiler shouldn't change the relative order or number of volatile
975 /// memory operations. However, volatile memory operations on zero-sized types
976 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
977 /// and may be ignored.
979 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
983 /// Behavior is undefined if any of the following conditions are violated:
985 /// * `dst` must be [valid] for writes.
987 /// * `dst` must be properly aligned.
989 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
991 /// [valid]: ../ptr/index.html#safety
993 /// Just like in C, whether an operation is volatile has no bearing whatsoever
994 /// on questions involving concurrent access from multiple threads. Volatile
995 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
996 /// a race between a `write_volatile` and any other operation (reading or writing)
997 /// on the same location is undefined behavior.
1005 /// let y = &mut x as *mut i32;
1009 /// std::ptr::write_volatile(y, z);
1010 /// assert_eq!(std::ptr::read_volatile(y), 12);
1014 #[stable(feature = "volatile", since = "1.9.0")]
1015 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
1016 intrinsics::volatile_store(dst, src);
1019 #[lang = "const_ptr"]
1020 impl<T: ?Sized> *const T {
1021 /// Returns `true` if the pointer is null.
1023 /// Note that unsized types have many possible null pointers, as only the
1024 /// raw data pointer is considered, not their length, vtable, etc.
1025 /// Therefore, two pointers that are null may still not compare equal to
1033 /// let s: &str = "Follow the rabbit";
1034 /// let ptr: *const u8 = s.as_ptr();
1035 /// assert!(!ptr.is_null());
1037 #[stable(feature = "rust1", since = "1.0.0")]
1039 pub fn is_null(self) -> bool {
1040 // Compare via a cast to a thin pointer, so fat pointers are only
1041 // considering their "data" part for null-ness.
1042 (self as *const u8) == null()
1045 /// Cast to a pointer to a different type
1046 #[stable(feature = "ptr_cast", since = "1.38.0")]
1048 pub const fn cast<U>(self) -> *const U {
1052 /// Returns `None` if the pointer is null, or else returns a reference to
1053 /// the value wrapped in `Some`.
1057 /// While this method and its mutable counterpart are useful for
1058 /// null-safety, it is important to note that this is still an unsafe
1059 /// operation because the returned value could be pointing to invalid
1062 /// When calling this method, you have to ensure that if the pointer is
1063 /// non-NULL, then it is properly aligned, dereferencable (for the whole
1064 /// size of `T`) and points to an initialized instance of `T`. This applies
1065 /// even if the result of this method is unused!
1066 /// (The part about being initialized is not yet fully decided, but until
1067 /// it is, the only safe approach is to ensure that they are indeed initialized.)
1069 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1070 /// not necessarily reflect the actual lifetime of the data. It is up to the
1071 /// caller to ensure that for the duration of this lifetime, the memory this
1072 /// pointer points to does not get written to outside of `UnsafeCell<U>`.
1079 /// let ptr: *const u8 = &10u8 as *const u8;
1082 /// if let Some(val_back) = ptr.as_ref() {
1083 /// println!("We got back the value: {}!", val_back);
1088 /// # Null-unchecked version
1090 /// If you are sure the pointer can never be null and are looking for some kind of
1091 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1092 /// dereference the pointer directly.
1095 /// let ptr: *const u8 = &10u8 as *const u8;
1098 /// let val_back = &*ptr;
1099 /// println!("We got back the value: {}!", val_back);
1102 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1104 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1112 /// Calculates the offset from a pointer.
1114 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1115 /// offset of `3 * size_of::<T>()` bytes.
1119 /// If any of the following conditions are violated, the result is Undefined
1122 /// * Both the starting and resulting pointer must be either in bounds or one
1123 /// byte past the end of the same allocated object.
1125 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1127 /// * The offset being in bounds cannot rely on "wrapping around" the address
1128 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1130 /// The compiler and standard library generally tries to ensure allocations
1131 /// never reach a size where an offset is a concern. For instance, `Vec`
1132 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1133 /// `vec.as_ptr().add(vec.len())` is always safe.
1135 /// Most platforms fundamentally can't even construct such an allocation.
1136 /// For instance, no known 64-bit platform can ever serve a request
1137 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1138 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1139 /// more than `isize::MAX` bytes with things like Physical Address
1140 /// Extension. As such, memory acquired directly from allocators or memory
1141 /// mapped files *may* be too large to handle with this function.
1143 /// Consider using `wrapping_offset` instead if these constraints are
1144 /// difficult to satisfy. The only advantage of this method is that it
1145 /// enables more aggressive compiler optimizations.
1152 /// let s: &str = "123";
1153 /// let ptr: *const u8 = s.as_ptr();
1156 /// println!("{}", *ptr.offset(1) as char);
1157 /// println!("{}", *ptr.offset(2) as char);
1160 #[stable(feature = "rust1", since = "1.0.0")]
1162 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
1163 intrinsics::offset(self, count)
1166 /// Calculates the offset from a pointer using wrapping arithmetic.
1168 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1169 /// offset of `3 * size_of::<T>()` bytes.
1173 /// The resulting pointer does not need to be in bounds, but it is
1174 /// potentially hazardous to dereference (which requires `unsafe`).
1175 /// In particular, the resulting pointer may *not* be used to access a
1176 /// different allocated object than the one `self` points to. In other
1177 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1178 /// *not* the same as `y`, and dereferencing it is undefined behavior
1179 /// unless `x` and `y` point into the same allocated object.
1181 /// Always use `.offset(count)` instead when possible, because `offset`
1182 /// allows the compiler to optimize better. If you need to cross object
1183 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1190 /// // Iterate using a raw pointer in increments of two elements
1191 /// let data = [1u8, 2, 3, 4, 5];
1192 /// let mut ptr: *const u8 = data.as_ptr();
1194 /// let end_rounded_up = ptr.wrapping_offset(6);
1196 /// // This loop prints "1, 3, 5, "
1197 /// while ptr != end_rounded_up {
1199 /// print!("{}, ", *ptr);
1201 /// ptr = ptr.wrapping_offset(step);
1204 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1206 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
1208 intrinsics::arith_offset(self, count)
1212 /// Calculates the distance between two pointers. The returned value is in
1213 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1215 /// This function is the inverse of [`offset`].
1217 /// [`offset`]: #method.offset
1218 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
1222 /// If any of the following conditions are violated, the result is Undefined
1225 /// * Both the starting and other pointer must be either in bounds or one
1226 /// byte past the end of the same allocated object.
1228 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1230 /// * The distance between the pointers, in bytes, must be an exact multiple
1231 /// of the size of `T`.
1233 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1235 /// The compiler and standard library generally try to ensure allocations
1236 /// never reach a size where an offset is a concern. For instance, `Vec`
1237 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1238 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1240 /// Most platforms fundamentally can't even construct such an allocation.
1241 /// For instance, no known 64-bit platform can ever serve a request
1242 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1243 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1244 /// more than `isize::MAX` bytes with things like Physical Address
1245 /// Extension. As such, memory acquired directly from allocators or memory
1246 /// mapped files *may* be too large to handle with this function.
1248 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1249 /// difficult to satisfy. The only advantage of this method is that it
1250 /// enables more aggressive compiler optimizations.
1254 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1261 /// #![feature(ptr_offset_from)]
1264 /// let ptr1: *const i32 = &a[1];
1265 /// let ptr2: *const i32 = &a[3];
1267 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1268 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1269 /// assert_eq!(ptr1.offset(2), ptr2);
1270 /// assert_eq!(ptr2.offset(-2), ptr1);
1273 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1275 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1276 let pointee_size = mem::size_of::<T>();
1277 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1279 // This is the same sequence that Clang emits for pointer subtraction.
1280 // It can be neither `nsw` nor `nuw` because the input is treated as
1281 // unsigned but then the output is treated as signed, so neither works.
1282 let d = isize::wrapping_sub(self as _, origin as _);
1283 intrinsics::exact_div(d, pointee_size as _)
1286 /// Calculates the distance between two pointers. The returned value is in
1287 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1289 /// If the address different between the two pointers is not a multiple of
1290 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1293 /// Though this method is safe for any two pointers, note that its result
1294 /// will be mostly useless if the two pointers aren't into the same allocated
1295 /// object, for example if they point to two different local variables.
1299 /// This function panics if `T` is a zero-sized type.
1306 /// #![feature(ptr_wrapping_offset_from)]
1309 /// let ptr1: *const i32 = &a[1];
1310 /// let ptr2: *const i32 = &a[3];
1311 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1312 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1313 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1314 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1316 /// let ptr1: *const i32 = 3 as _;
1317 /// let ptr2: *const i32 = 13 as _;
1318 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1320 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1322 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1323 let pointee_size = mem::size_of::<T>();
1324 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1326 let d = isize::wrapping_sub(self as _, origin as _);
1327 d.wrapping_div(pointee_size as _)
1330 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1332 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1333 /// offset of `3 * size_of::<T>()` bytes.
1337 /// If any of the following conditions are violated, the result is Undefined
1340 /// * Both the starting and resulting pointer must be either in bounds or one
1341 /// byte past the end of the same allocated object.
1343 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1345 /// * The offset being in bounds cannot rely on "wrapping around" the address
1346 /// space. That is, the infinite-precision sum must fit in a `usize`.
1348 /// The compiler and standard library generally tries to ensure allocations
1349 /// never reach a size where an offset is a concern. For instance, `Vec`
1350 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1351 /// `vec.as_ptr().add(vec.len())` is always safe.
1353 /// Most platforms fundamentally can't even construct such an allocation.
1354 /// For instance, no known 64-bit platform can ever serve a request
1355 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1356 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1357 /// more than `isize::MAX` bytes with things like Physical Address
1358 /// Extension. As such, memory acquired directly from allocators or memory
1359 /// mapped files *may* be too large to handle with this function.
1361 /// Consider using `wrapping_offset` instead if these constraints are
1362 /// difficult to satisfy. The only advantage of this method is that it
1363 /// enables more aggressive compiler optimizations.
1370 /// let s: &str = "123";
1371 /// let ptr: *const u8 = s.as_ptr();
1374 /// println!("{}", *ptr.add(1) as char);
1375 /// println!("{}", *ptr.add(2) as char);
1378 #[stable(feature = "pointer_methods", since = "1.26.0")]
1380 pub unsafe fn add(self, count: usize) -> Self
1383 self.offset(count as isize)
1386 /// Calculates the offset from a pointer (convenience for
1387 /// `.offset((count as isize).wrapping_neg())`).
1389 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1390 /// offset of `3 * size_of::<T>()` bytes.
1394 /// If any of the following conditions are violated, the result is Undefined
1397 /// * Both the starting and resulting pointer must be either in bounds or one
1398 /// byte past the end of the same allocated object.
1400 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1402 /// * The offset being in bounds cannot rely on "wrapping around" the address
1403 /// space. That is, the infinite-precision sum must fit in a usize.
1405 /// The compiler and standard library generally tries to ensure allocations
1406 /// never reach a size where an offset is a concern. For instance, `Vec`
1407 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1408 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1410 /// Most platforms fundamentally can't even construct such an allocation.
1411 /// For instance, no known 64-bit platform can ever serve a request
1412 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1413 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1414 /// more than `isize::MAX` bytes with things like Physical Address
1415 /// Extension. As such, memory acquired directly from allocators or memory
1416 /// mapped files *may* be too large to handle with this function.
1418 /// Consider using `wrapping_offset` instead if these constraints are
1419 /// difficult to satisfy. The only advantage of this method is that it
1420 /// enables more aggressive compiler optimizations.
1427 /// let s: &str = "123";
1430 /// let end: *const u8 = s.as_ptr().add(3);
1431 /// println!("{}", *end.sub(1) as char);
1432 /// println!("{}", *end.sub(2) as char);
1435 #[stable(feature = "pointer_methods", since = "1.26.0")]
1437 pub unsafe fn sub(self, count: usize) -> Self
1440 self.offset((count as isize).wrapping_neg())
1443 /// Calculates the offset from a pointer using wrapping arithmetic.
1444 /// (convenience for `.wrapping_offset(count as isize)`)
1446 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1447 /// offset of `3 * size_of::<T>()` bytes.
1451 /// The resulting pointer does not need to be in bounds, but it is
1452 /// potentially hazardous to dereference (which requires `unsafe`).
1454 /// Always use `.add(count)` instead when possible, because `add`
1455 /// allows the compiler to optimize better.
1462 /// // Iterate using a raw pointer in increments of two elements
1463 /// let data = [1u8, 2, 3, 4, 5];
1464 /// let mut ptr: *const u8 = data.as_ptr();
1466 /// let end_rounded_up = ptr.wrapping_add(6);
1468 /// // This loop prints "1, 3, 5, "
1469 /// while ptr != end_rounded_up {
1471 /// print!("{}, ", *ptr);
1473 /// ptr = ptr.wrapping_add(step);
1476 #[stable(feature = "pointer_methods", since = "1.26.0")]
1478 pub fn wrapping_add(self, count: usize) -> Self
1481 self.wrapping_offset(count as isize)
1484 /// Calculates the offset from a pointer using wrapping arithmetic.
1485 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1487 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1488 /// offset of `3 * size_of::<T>()` bytes.
1492 /// The resulting pointer does not need to be in bounds, but it is
1493 /// potentially hazardous to dereference (which requires `unsafe`).
1495 /// Always use `.sub(count)` instead when possible, because `sub`
1496 /// allows the compiler to optimize better.
1503 /// // Iterate using a raw pointer in increments of two elements (backwards)
1504 /// let data = [1u8, 2, 3, 4, 5];
1505 /// let mut ptr: *const u8 = data.as_ptr();
1506 /// let start_rounded_down = ptr.wrapping_sub(2);
1507 /// ptr = ptr.wrapping_add(4);
1509 /// // This loop prints "5, 3, 1, "
1510 /// while ptr != start_rounded_down {
1512 /// print!("{}, ", *ptr);
1514 /// ptr = ptr.wrapping_sub(step);
1517 #[stable(feature = "pointer_methods", since = "1.26.0")]
1519 pub fn wrapping_sub(self, count: usize) -> Self
1522 self.wrapping_offset((count as isize).wrapping_neg())
1525 /// Reads the value from `self` without moving it. This leaves the
1526 /// memory in `self` unchanged.
1528 /// See [`ptr::read`] for safety concerns and examples.
1530 /// [`ptr::read`]: ./ptr/fn.read.html
1531 #[stable(feature = "pointer_methods", since = "1.26.0")]
1533 pub unsafe fn read(self) -> T
1539 /// Performs a volatile read of the value from `self` without moving it. This
1540 /// leaves the memory in `self` unchanged.
1542 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1543 /// to not be elided or reordered by the compiler across other volatile
1546 /// See [`ptr::read_volatile`] for safety concerns and examples.
1548 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
1549 #[stable(feature = "pointer_methods", since = "1.26.0")]
1551 pub unsafe fn read_volatile(self) -> T
1557 /// Reads the value from `self` without moving it. This leaves the
1558 /// memory in `self` unchanged.
1560 /// Unlike `read`, the pointer may be unaligned.
1562 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1564 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
1565 #[stable(feature = "pointer_methods", since = "1.26.0")]
1567 pub unsafe fn read_unaligned(self) -> T
1570 read_unaligned(self)
1573 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1574 /// and destination may overlap.
1576 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1578 /// See [`ptr::copy`] for safety concerns and examples.
1580 /// [`ptr::copy`]: ./ptr/fn.copy.html
1581 #[stable(feature = "pointer_methods", since = "1.26.0")]
1583 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1586 copy(self, dest, count)
1589 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1590 /// and destination may *not* overlap.
1592 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1594 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1596 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
1597 #[stable(feature = "pointer_methods", since = "1.26.0")]
1599 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1602 copy_nonoverlapping(self, dest, count)
1605 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1608 /// If it is not possible to align the pointer, the implementation returns
1609 /// `usize::max_value()`.
1611 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1612 /// used with the `offset` or `offset_to` methods.
1614 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
1615 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1616 /// the returned offset is correct in all terms other than alignment.
1620 /// The function panics if `align` is not a power-of-two.
1624 /// Accessing adjacent `u8` as `u16`
1627 /// # fn foo(n: usize) {
1628 /// # use std::mem::align_of;
1630 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1631 /// let ptr = &x[n] as *const u8;
1632 /// let offset = ptr.align_offset(align_of::<u16>());
1633 /// if offset < x.len() - n - 1 {
1634 /// let u16_ptr = ptr.add(offset) as *const u16;
1635 /// assert_ne!(*u16_ptr, 500);
1637 /// // while the pointer can be aligned via `offset`, it would point
1638 /// // outside the allocation
1642 #[stable(feature = "align_offset", since = "1.36.0")]
1643 pub fn align_offset(self, align: usize) -> usize where T: Sized {
1644 if !align.is_power_of_two() {
1645 panic!("align_offset: align is not a power-of-two");
1648 align_offset(self, align)
1655 impl<T: ?Sized> *mut T {
1656 /// Returns `true` if the pointer is null.
1658 /// Note that unsized types have many possible null pointers, as only the
1659 /// raw data pointer is considered, not their length, vtable, etc.
1660 /// Therefore, two pointers that are null may still not compare equal to
1668 /// let mut s = [1, 2, 3];
1669 /// let ptr: *mut u32 = s.as_mut_ptr();
1670 /// assert!(!ptr.is_null());
1672 #[stable(feature = "rust1", since = "1.0.0")]
1674 pub fn is_null(self) -> bool {
1675 // Compare via a cast to a thin pointer, so fat pointers are only
1676 // considering their "data" part for null-ness.
1677 (self as *mut u8) == null_mut()
1680 /// Cast to a pointer to a different type
1681 #[stable(feature = "ptr_cast", since = "1.38.0")]
1683 pub const fn cast<U>(self) -> *mut U {
1687 /// Returns `None` if the pointer is null, or else returns a reference to
1688 /// the value wrapped in `Some`.
1692 /// While this method and its mutable counterpart are useful for
1693 /// null-safety, it is important to note that this is still an unsafe
1694 /// operation because the returned value could be pointing to invalid
1697 /// When calling this method, you have to ensure that if the pointer is
1698 /// non-NULL, then it is properly aligned, dereferencable (for the whole
1699 /// size of `T`) and points to an initialized instance of `T`. This applies
1700 /// even if the result of this method is unused!
1701 /// (The part about being initialized is not yet fully decided, but until
1702 /// it is, the only safe approach is to ensure that they are indeed initialized.)
1704 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1705 /// not necessarily reflect the actual lifetime of the data. It is up to the
1706 /// caller to ensure that for the duration of this lifetime, the memory this
1707 /// pointer points to does not get written to outside of `UnsafeCell<U>`.
1714 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1717 /// if let Some(val_back) = ptr.as_ref() {
1718 /// println!("We got back the value: {}!", val_back);
1723 /// # Null-unchecked version
1725 /// If you are sure the pointer can never be null and are looking for some kind of
1726 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1727 /// dereference the pointer directly.
1730 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1733 /// let val_back = &*ptr;
1734 /// println!("We got back the value: {}!", val_back);
1737 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1739 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1747 /// Calculates the offset from a pointer.
1749 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1750 /// offset of `3 * size_of::<T>()` bytes.
1754 /// If any of the following conditions are violated, the result is Undefined
1757 /// * Both the starting and resulting pointer must be either in bounds or one
1758 /// byte past the end of the same allocated object.
1760 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1762 /// * The offset being in bounds cannot rely on "wrapping around" the address
1763 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1765 /// The compiler and standard library generally tries to ensure allocations
1766 /// never reach a size where an offset is a concern. For instance, `Vec`
1767 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1768 /// `vec.as_ptr().add(vec.len())` is always safe.
1770 /// Most platforms fundamentally can't even construct such an allocation.
1771 /// For instance, no known 64-bit platform can ever serve a request
1772 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1773 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1774 /// more than `isize::MAX` bytes with things like Physical Address
1775 /// Extension. As such, memory acquired directly from allocators or memory
1776 /// mapped files *may* be too large to handle with this function.
1778 /// Consider using `wrapping_offset` instead if these constraints are
1779 /// difficult to satisfy. The only advantage of this method is that it
1780 /// enables more aggressive compiler optimizations.
1787 /// let mut s = [1, 2, 3];
1788 /// let ptr: *mut u32 = s.as_mut_ptr();
1791 /// println!("{}", *ptr.offset(1));
1792 /// println!("{}", *ptr.offset(2));
1795 #[stable(feature = "rust1", since = "1.0.0")]
1797 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1798 intrinsics::offset(self, count) as *mut T
1801 /// Calculates the offset from a pointer using wrapping arithmetic.
1802 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1803 /// offset of `3 * size_of::<T>()` bytes.
1807 /// The resulting pointer does not need to be in bounds, but it is
1808 /// potentially hazardous to dereference (which requires `unsafe`).
1809 /// In particular, the resulting pointer may *not* be used to access a
1810 /// different allocated object than the one `self` points to. In other
1811 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1812 /// *not* the same as `y`, and dereferencing it is undefined behavior
1813 /// unless `x` and `y` point into the same allocated object.
1815 /// Always use `.offset(count)` instead when possible, because `offset`
1816 /// allows the compiler to optimize better. If you need to cross object
1817 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1824 /// // Iterate using a raw pointer in increments of two elements
1825 /// let mut data = [1u8, 2, 3, 4, 5];
1826 /// let mut ptr: *mut u8 = data.as_mut_ptr();
1828 /// let end_rounded_up = ptr.wrapping_offset(6);
1830 /// while ptr != end_rounded_up {
1834 /// ptr = ptr.wrapping_offset(step);
1836 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1838 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1840 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1842 intrinsics::arith_offset(self, count) as *mut T
1846 /// Returns `None` if the pointer is null, or else returns a mutable
1847 /// reference to the value wrapped in `Some`.
1851 /// As with [`as_ref`], this is unsafe because it cannot verify the validity
1852 /// of the returned pointer, nor can it ensure that the lifetime `'a`
1853 /// returned is indeed a valid lifetime for the contained data.
1855 /// When calling this method, you have to ensure that if the pointer is
1856 /// non-NULL, then it is properly aligned, dereferencable (for the whole
1857 /// size of `T`) and points to an initialized instance of `T`. This applies
1858 /// even if the result of this method is unused!
1859 /// (The part about being initialized is not yet fully decided, but until
1860 /// it is the only safe approach is to ensure that they are indeed initialized.)
1862 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1863 /// not necessarily reflect the actual lifetime of the data. It is up to the
1864 /// caller to ensure that for the duration of this lifetime, the memory this
1865 /// pointer points to does not get accessed through any other pointer.
1867 /// [`as_ref`]: #method.as_ref
1874 /// let mut s = [1, 2, 3];
1875 /// let ptr: *mut u32 = s.as_mut_ptr();
1876 /// let first_value = unsafe { ptr.as_mut().unwrap() };
1877 /// *first_value = 4;
1878 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1880 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1882 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1890 /// Calculates the distance between two pointers. The returned value is in
1891 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1893 /// This function is the inverse of [`offset`].
1895 /// [`offset`]: #method.offset-1
1896 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
1900 /// If any of the following conditions are violated, the result is Undefined
1903 /// * Both the starting and other pointer must be either in bounds or one
1904 /// byte past the end of the same allocated object.
1906 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1908 /// * The distance between the pointers, in bytes, must be an exact multiple
1909 /// of the size of `T`.
1911 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1913 /// The compiler and standard library generally try to ensure allocations
1914 /// never reach a size where an offset is a concern. For instance, `Vec`
1915 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1916 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1918 /// Most platforms fundamentally can't even construct such an allocation.
1919 /// For instance, no known 64-bit platform can ever serve a request
1920 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1921 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1922 /// more than `isize::MAX` bytes with things like Physical Address
1923 /// Extension. As such, memory acquired directly from allocators or memory
1924 /// mapped files *may* be too large to handle with this function.
1926 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1927 /// difficult to satisfy. The only advantage of this method is that it
1928 /// enables more aggressive compiler optimizations.
1932 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1939 /// #![feature(ptr_offset_from)]
1941 /// let mut a = [0; 5];
1942 /// let ptr1: *mut i32 = &mut a[1];
1943 /// let ptr2: *mut i32 = &mut a[3];
1945 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1946 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1947 /// assert_eq!(ptr1.offset(2), ptr2);
1948 /// assert_eq!(ptr2.offset(-2), ptr1);
1951 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1953 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1954 (self as *const T).offset_from(origin)
1957 /// Calculates the distance between two pointers. The returned value is in
1958 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1960 /// If the address different between the two pointers is not a multiple of
1961 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1964 /// Though this method is safe for any two pointers, note that its result
1965 /// will be mostly useless if the two pointers aren't into the same allocated
1966 /// object, for example if they point to two different local variables.
1970 /// This function panics if `T` is a zero-sized type.
1977 /// #![feature(ptr_wrapping_offset_from)]
1979 /// let mut a = [0; 5];
1980 /// let ptr1: *mut i32 = &mut a[1];
1981 /// let ptr2: *mut i32 = &mut a[3];
1982 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1983 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1984 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1985 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1987 /// let ptr1: *mut i32 = 3 as _;
1988 /// let ptr2: *mut i32 = 13 as _;
1989 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1991 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1993 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1994 (self as *const T).wrapping_offset_from(origin)
1997 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1999 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2000 /// offset of `3 * size_of::<T>()` bytes.
2004 /// If any of the following conditions are violated, the result is Undefined
2007 /// * Both the starting and resulting pointer must be either in bounds or one
2008 /// byte past the end of the same allocated object.
2010 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
2012 /// * The offset being in bounds cannot rely on "wrapping around" the address
2013 /// space. That is, the infinite-precision sum must fit in a `usize`.
2015 /// The compiler and standard library generally tries to ensure allocations
2016 /// never reach a size where an offset is a concern. For instance, `Vec`
2017 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
2018 /// `vec.as_ptr().add(vec.len())` is always safe.
2020 /// Most platforms fundamentally can't even construct such an allocation.
2021 /// For instance, no known 64-bit platform can ever serve a request
2022 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
2023 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
2024 /// more than `isize::MAX` bytes with things like Physical Address
2025 /// Extension. As such, memory acquired directly from allocators or memory
2026 /// mapped files *may* be too large to handle with this function.
2028 /// Consider using `wrapping_offset` instead if these constraints are
2029 /// difficult to satisfy. The only advantage of this method is that it
2030 /// enables more aggressive compiler optimizations.
2037 /// let s: &str = "123";
2038 /// let ptr: *const u8 = s.as_ptr();
2041 /// println!("{}", *ptr.add(1) as char);
2042 /// println!("{}", *ptr.add(2) as char);
2045 #[stable(feature = "pointer_methods", since = "1.26.0")]
2047 pub unsafe fn add(self, count: usize) -> Self
2050 self.offset(count as isize)
2053 /// Calculates the offset from a pointer (convenience for
2054 /// `.offset((count as isize).wrapping_neg())`).
2056 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2057 /// offset of `3 * size_of::<T>()` bytes.
2061 /// If any of the following conditions are violated, the result is Undefined
2064 /// * Both the starting and resulting pointer must be either in bounds or one
2065 /// byte past the end of the same allocated object.
2067 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
2069 /// * The offset being in bounds cannot rely on "wrapping around" the address
2070 /// space. That is, the infinite-precision sum must fit in a usize.
2072 /// The compiler and standard library generally tries to ensure allocations
2073 /// never reach a size where an offset is a concern. For instance, `Vec`
2074 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
2075 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
2077 /// Most platforms fundamentally can't even construct such an allocation.
2078 /// For instance, no known 64-bit platform can ever serve a request
2079 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
2080 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
2081 /// more than `isize::MAX` bytes with things like Physical Address
2082 /// Extension. As such, memory acquired directly from allocators or memory
2083 /// mapped files *may* be too large to handle with this function.
2085 /// Consider using `wrapping_offset` instead if these constraints are
2086 /// difficult to satisfy. The only advantage of this method is that it
2087 /// enables more aggressive compiler optimizations.
2094 /// let s: &str = "123";
2097 /// let end: *const u8 = s.as_ptr().add(3);
2098 /// println!("{}", *end.sub(1) as char);
2099 /// println!("{}", *end.sub(2) as char);
2102 #[stable(feature = "pointer_methods", since = "1.26.0")]
2104 pub unsafe fn sub(self, count: usize) -> Self
2107 self.offset((count as isize).wrapping_neg())
2110 /// Calculates the offset from a pointer using wrapping arithmetic.
2111 /// (convenience for `.wrapping_offset(count as isize)`)
2113 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2114 /// offset of `3 * size_of::<T>()` bytes.
2118 /// The resulting pointer does not need to be in bounds, but it is
2119 /// potentially hazardous to dereference (which requires `unsafe`).
2121 /// Always use `.add(count)` instead when possible, because `add`
2122 /// allows the compiler to optimize better.
2129 /// // Iterate using a raw pointer in increments of two elements
2130 /// let data = [1u8, 2, 3, 4, 5];
2131 /// let mut ptr: *const u8 = data.as_ptr();
2133 /// let end_rounded_up = ptr.wrapping_add(6);
2135 /// // This loop prints "1, 3, 5, "
2136 /// while ptr != end_rounded_up {
2138 /// print!("{}, ", *ptr);
2140 /// ptr = ptr.wrapping_add(step);
2143 #[stable(feature = "pointer_methods", since = "1.26.0")]
2145 pub fn wrapping_add(self, count: usize) -> Self
2148 self.wrapping_offset(count as isize)
2151 /// Calculates the offset from a pointer using wrapping arithmetic.
2152 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
2154 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2155 /// offset of `3 * size_of::<T>()` bytes.
2159 /// The resulting pointer does not need to be in bounds, but it is
2160 /// potentially hazardous to dereference (which requires `unsafe`).
2162 /// Always use `.sub(count)` instead when possible, because `sub`
2163 /// allows the compiler to optimize better.
2170 /// // Iterate using a raw pointer in increments of two elements (backwards)
2171 /// let data = [1u8, 2, 3, 4, 5];
2172 /// let mut ptr: *const u8 = data.as_ptr();
2173 /// let start_rounded_down = ptr.wrapping_sub(2);
2174 /// ptr = ptr.wrapping_add(4);
2176 /// // This loop prints "5, 3, 1, "
2177 /// while ptr != start_rounded_down {
2179 /// print!("{}, ", *ptr);
2181 /// ptr = ptr.wrapping_sub(step);
2184 #[stable(feature = "pointer_methods", since = "1.26.0")]
2186 pub fn wrapping_sub(self, count: usize) -> Self
2189 self.wrapping_offset((count as isize).wrapping_neg())
2192 /// Reads the value from `self` without moving it. This leaves the
2193 /// memory in `self` unchanged.
2195 /// See [`ptr::read`] for safety concerns and examples.
2197 /// [`ptr::read`]: ./ptr/fn.read.html
2198 #[stable(feature = "pointer_methods", since = "1.26.0")]
2200 pub unsafe fn read(self) -> T
2206 /// Performs a volatile read of the value from `self` without moving it. This
2207 /// leaves the memory in `self` unchanged.
2209 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2210 /// to not be elided or reordered by the compiler across other volatile
2213 /// See [`ptr::read_volatile`] for safety concerns and examples.
2215 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
2216 #[stable(feature = "pointer_methods", since = "1.26.0")]
2218 pub unsafe fn read_volatile(self) -> T
2224 /// Reads the value from `self` without moving it. This leaves the
2225 /// memory in `self` unchanged.
2227 /// Unlike `read`, the pointer may be unaligned.
2229 /// See [`ptr::read_unaligned`] for safety concerns and examples.
2231 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
2232 #[stable(feature = "pointer_methods", since = "1.26.0")]
2234 pub unsafe fn read_unaligned(self) -> T
2237 read_unaligned(self)
2240 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2241 /// and destination may overlap.
2243 /// NOTE: this has the *same* argument order as [`ptr::copy`].
2245 /// See [`ptr::copy`] for safety concerns and examples.
2247 /// [`ptr::copy`]: ./ptr/fn.copy.html
2248 #[stable(feature = "pointer_methods", since = "1.26.0")]
2250 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
2253 copy(self, dest, count)
2256 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2257 /// and destination may *not* overlap.
2259 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
2261 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2263 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2264 #[stable(feature = "pointer_methods", since = "1.26.0")]
2266 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
2269 copy_nonoverlapping(self, dest, count)
2272 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2273 /// and destination may overlap.
2275 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
2277 /// See [`ptr::copy`] for safety concerns and examples.
2279 /// [`ptr::copy`]: ./ptr/fn.copy.html
2280 #[stable(feature = "pointer_methods", since = "1.26.0")]
2282 pub unsafe fn copy_from(self, src: *const T, count: usize)
2285 copy(src, self, count)
2288 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2289 /// and destination may *not* overlap.
2291 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
2293 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2295 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2296 #[stable(feature = "pointer_methods", since = "1.26.0")]
2298 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
2301 copy_nonoverlapping(src, self, count)
2304 /// Executes the destructor (if any) of the pointed-to value.
2306 /// See [`ptr::drop_in_place`] for safety concerns and examples.
2308 /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
2309 #[stable(feature = "pointer_methods", since = "1.26.0")]
2311 pub unsafe fn drop_in_place(self) {
2315 /// Overwrites a memory location with the given value without reading or
2316 /// dropping the old value.
2318 /// See [`ptr::write`] for safety concerns and examples.
2320 /// [`ptr::write`]: ./ptr/fn.write.html
2321 #[stable(feature = "pointer_methods", since = "1.26.0")]
2323 pub unsafe fn write(self, val: T)
2329 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
2330 /// bytes of memory starting at `self` to `val`.
2332 /// See [`ptr::write_bytes`] for safety concerns and examples.
2334 /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
2335 #[stable(feature = "pointer_methods", since = "1.26.0")]
2337 pub unsafe fn write_bytes(self, val: u8, count: usize)
2340 write_bytes(self, val, count)
2343 /// Performs a volatile write of a memory location with the given value without
2344 /// reading or dropping the old value.
2346 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2347 /// to not be elided or reordered by the compiler across other volatile
2350 /// See [`ptr::write_volatile`] for safety concerns and examples.
2352 /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
2353 #[stable(feature = "pointer_methods", since = "1.26.0")]
2355 pub unsafe fn write_volatile(self, val: T)
2358 write_volatile(self, val)
2361 /// Overwrites a memory location with the given value without reading or
2362 /// dropping the old value.
2364 /// Unlike `write`, the pointer may be unaligned.
2366 /// See [`ptr::write_unaligned`] for safety concerns and examples.
2368 /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
2369 #[stable(feature = "pointer_methods", since = "1.26.0")]
2371 pub unsafe fn write_unaligned(self, val: T)
2374 write_unaligned(self, val)
2377 /// Replaces the value at `self` with `src`, returning the old
2378 /// value, without dropping either.
2380 /// See [`ptr::replace`] for safety concerns and examples.
2382 /// [`ptr::replace`]: ./ptr/fn.replace.html
2383 #[stable(feature = "pointer_methods", since = "1.26.0")]
2385 pub unsafe fn replace(self, src: T) -> T
2391 /// Swaps the values at two mutable locations of the same type, without
2392 /// deinitializing either. They may overlap, unlike `mem::swap` which is
2393 /// otherwise equivalent.
2395 /// See [`ptr::swap`] for safety concerns and examples.
2397 /// [`ptr::swap`]: ./ptr/fn.swap.html
2398 #[stable(feature = "pointer_methods", since = "1.26.0")]
2400 pub unsafe fn swap(self, with: *mut T)
2406 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
2409 /// If it is not possible to align the pointer, the implementation returns
2410 /// `usize::max_value()`.
2412 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
2413 /// used with the `offset` or `offset_to` methods.
2415 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
2416 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
2417 /// the returned offset is correct in all terms other than alignment.
2421 /// The function panics if `align` is not a power-of-two.
2425 /// Accessing adjacent `u8` as `u16`
2428 /// # fn foo(n: usize) {
2429 /// # use std::mem::align_of;
2431 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
2432 /// let ptr = &x[n] as *const u8;
2433 /// let offset = ptr.align_offset(align_of::<u16>());
2434 /// if offset < x.len() - n - 1 {
2435 /// let u16_ptr = ptr.add(offset) as *const u16;
2436 /// assert_ne!(*u16_ptr, 500);
2438 /// // while the pointer can be aligned via `offset`, it would point
2439 /// // outside the allocation
2443 #[stable(feature = "align_offset", since = "1.36.0")]
2444 pub fn align_offset(self, align: usize) -> usize where T: Sized {
2445 if !align.is_power_of_two() {
2446 panic!("align_offset: align is not a power-of-two");
2449 align_offset(self, align)
2454 /// Align pointer `p`.
2456 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
2457 /// to pointer `p` so that pointer `p` would get aligned to `a`.
2459 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
2460 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2463 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2464 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2465 /// than trying to adapt this to accommodate that change.
2467 /// Any questions go to @nagisa.
2468 #[lang="align_offset"]
2469 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2470 /// Calculate multiplicative modular inverse of `x` modulo `m`.
2472 /// This implementation is tailored for align_offset and has following preconditions:
2474 /// * `m` is a power-of-two;
2475 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2477 /// Implementation of this function shall not panic. Ever.
2479 fn mod_inv(x: usize, m: usize) -> usize {
2480 /// Multiplicative modular inverse table modulo 2⁴ = 16.
2482 /// Note, that this table does not contain values where inverse does not exist (i.e., for
2483 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2484 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2485 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2486 const INV_TABLE_MOD: usize = 16;
2488 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
2490 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
2491 if m <= INV_TABLE_MOD {
2492 table_inverse & (m - 1)
2494 // We iterate "up" using the following formula:
2496 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2498 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
2499 let mut inverse = table_inverse;
2500 let mut going_mod = INV_TABLE_MOD_SQUARED;
2502 // y = y * (2 - xy) mod n
2504 // Note, that we use wrapping operations here intentionally – the original formula
2505 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
2506 // usize::max_value()` instead, because we take the result `mod n` at the end
2508 inverse = inverse.wrapping_mul(
2509 2usize.wrapping_sub(x.wrapping_mul(inverse))
2510 ) & (going_mod - 1);
2512 return inverse & (m - 1);
2514 going_mod = going_mod.wrapping_mul(going_mod);
2519 let stride = mem::size_of::<T>();
2520 let a_minus_one = a.wrapping_sub(1);
2521 let pmoda = p as usize & a_minus_one;
2524 // Already aligned. Yay!
2529 return if stride == 0 {
2530 // If the pointer is not aligned, and the element is zero-sized, then no amount of
2531 // elements will ever align the pointer.
2534 a.wrapping_sub(pmoda)
2538 let smoda = stride & a_minus_one;
2539 // a is power-of-two so cannot be 0. stride = 0 is handled above.
2540 let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
2541 let gcd = 1usize << gcdpow;
2543 if p as usize & (gcd - 1) == 0 {
2544 // This branch solves for the following linear congruence equation:
2546 // $$ p + so ≡ 0 mod a $$
2548 // $p$ here is the pointer value, $s$ – stride of `T`, $o$ offset in `T`s, and $a$ – the
2549 // requested alignment.
2552 // o = (a - (p mod a))/g * ((s/g)⁻¹ mod a)
2554 // The first term is “the relative alignment of p to a”, the second term is “how does
2555 // incrementing p by s bytes change the relative alignment of p”. Division by `g` is
2556 // necessary to make this equation well formed if $a$ and $s$ are not co-prime.
2558 // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
2559 // to take the result $o mod lcm(s, a)$. We can replace $lcm(s, a)$ with just a $a / g$.
2560 let j = a.wrapping_sub(pmoda) >> gcdpow;
2561 let k = smoda >> gcdpow;
2562 return intrinsics::unchecked_rem(j.wrapping_mul(mod_inv(k, a)), a >> gcdpow);
2565 // Cannot be aligned at all.
2571 // Equality for pointers
2572 #[stable(feature = "rust1", since = "1.0.0")]
2573 impl<T: ?Sized> PartialEq for *const T {
2575 fn eq(&self, other: &*const T) -> bool { *self == *other }
2578 #[stable(feature = "rust1", since = "1.0.0")]
2579 impl<T: ?Sized> Eq for *const T {}
2581 #[stable(feature = "rust1", since = "1.0.0")]
2582 impl<T: ?Sized> PartialEq for *mut T {
2584 fn eq(&self, other: &*mut T) -> bool { *self == *other }
2587 #[stable(feature = "rust1", since = "1.0.0")]
2588 impl<T: ?Sized> Eq for *mut T {}
2590 /// Compares raw pointers for equality.
2592 /// This is the same as using the `==` operator, but less generic:
2593 /// the arguments have to be `*const T` raw pointers,
2594 /// not anything that implements `PartialEq`.
2596 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2597 /// by their address rather than comparing the values they point to
2598 /// (which is what the `PartialEq for &T` implementation does).
2606 /// let other_five = 5;
2607 /// let five_ref = &five;
2608 /// let same_five_ref = &five;
2609 /// let other_five_ref = &other_five;
2611 /// assert!(five_ref == same_five_ref);
2612 /// assert!(ptr::eq(five_ref, same_five_ref));
2614 /// assert!(five_ref == other_five_ref);
2615 /// assert!(!ptr::eq(five_ref, other_five_ref));
2618 /// Slices are also compared by their length (fat pointers):
2621 /// let a = [1, 2, 3];
2622 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
2623 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
2624 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
2627 /// Traits are also compared by their implementation:
2630 /// #[repr(transparent)]
2631 /// struct Wrapper { member: i32 }
2634 /// impl Trait for Wrapper {}
2635 /// impl Trait for i32 {}
2638 /// let wrapper = Wrapper { member: 10 };
2640 /// // Pointers have equal addresses.
2641 /// assert!(std::ptr::eq(
2642 /// &wrapper as *const Wrapper as *const u8,
2643 /// &wrapper.member as *const i32 as *const u8
2646 /// // Objects have equal addresses, but `Trait` has different implementations.
2647 /// assert!(!std::ptr::eq(
2648 /// &wrapper as &dyn Trait,
2649 /// &wrapper.member as &dyn Trait,
2651 /// assert!(!std::ptr::eq(
2652 /// &wrapper as &dyn Trait as *const dyn Trait,
2653 /// &wrapper.member as &dyn Trait as *const dyn Trait,
2656 /// // Converting the reference to a `*const u8` compares by address.
2657 /// assert!(std::ptr::eq(
2658 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
2659 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
2663 #[stable(feature = "ptr_eq", since = "1.17.0")]
2665 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2669 /// Hash a raw pointer.
2671 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
2672 /// by its address rather than the value it points to
2673 /// (which is what the `Hash for &T` implementation does).
2678 /// use std::collections::hash_map::DefaultHasher;
2679 /// use std::hash::{Hash, Hasher};
2683 /// let five_ref = &five;
2685 /// let mut hasher = DefaultHasher::new();
2686 /// ptr::hash(five_ref, &mut hasher);
2687 /// let actual = hasher.finish();
2689 /// let mut hasher = DefaultHasher::new();
2690 /// (five_ref as *const i32).hash(&mut hasher);
2691 /// let expected = hasher.finish();
2693 /// assert_eq!(actual, expected);
2695 #[stable(feature = "ptr_hash", since = "1.35.0")]
2696 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
2697 use crate::hash::Hash;
2701 // Impls for function pointers
2702 macro_rules! fnptr_impls_safety_abi {
2703 ($FnTy: ty, $($Arg: ident),*) => {
2704 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2705 impl<Ret, $($Arg),*> PartialEq for $FnTy {
2707 fn eq(&self, other: &Self) -> bool {
2708 *self as usize == *other as usize
2712 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2713 impl<Ret, $($Arg),*> Eq for $FnTy {}
2715 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2716 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2718 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2719 (*self as usize).partial_cmp(&(*other as usize))
2723 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2724 impl<Ret, $($Arg),*> Ord for $FnTy {
2726 fn cmp(&self, other: &Self) -> Ordering {
2727 (*self as usize).cmp(&(*other as usize))
2731 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2732 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2733 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2734 state.write_usize(*self as usize)
2738 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2739 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2741 fmt::Pointer::fmt(&(*self as *const ()), f)
2745 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2746 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2747 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2748 fmt::Pointer::fmt(&(*self as *const ()), f)
2754 macro_rules! fnptr_impls_args {
2755 ($($Arg: ident),+) => {
2756 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
2757 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
2758 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
2759 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
2760 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
2761 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
2764 // No variadic functions with 0 parameters
2765 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2766 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2767 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2768 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2772 fnptr_impls_args! { }
2773 fnptr_impls_args! { A }
2774 fnptr_impls_args! { A, B }
2775 fnptr_impls_args! { A, B, C }
2776 fnptr_impls_args! { A, B, C, D }
2777 fnptr_impls_args! { A, B, C, D, E }
2778 fnptr_impls_args! { A, B, C, D, E, F }
2779 fnptr_impls_args! { A, B, C, D, E, F, G }
2780 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2781 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2782 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2783 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2784 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2786 // Comparison for pointers
2787 #[stable(feature = "rust1", since = "1.0.0")]
2788 impl<T: ?Sized> Ord for *const T {
2790 fn cmp(&self, other: &*const T) -> Ordering {
2793 } else if self == other {
2801 #[stable(feature = "rust1", since = "1.0.0")]
2802 impl<T: ?Sized> PartialOrd for *const T {
2804 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2805 Some(self.cmp(other))
2809 fn lt(&self, other: &*const T) -> bool { *self < *other }
2812 fn le(&self, other: &*const T) -> bool { *self <= *other }
2815 fn gt(&self, other: &*const T) -> bool { *self > *other }
2818 fn ge(&self, other: &*const T) -> bool { *self >= *other }
2821 #[stable(feature = "rust1", since = "1.0.0")]
2822 impl<T: ?Sized> Ord for *mut T {
2824 fn cmp(&self, other: &*mut T) -> Ordering {
2827 } else if self == other {
2835 #[stable(feature = "rust1", since = "1.0.0")]
2836 impl<T: ?Sized> PartialOrd for *mut T {
2838 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2839 Some(self.cmp(other))
2843 fn lt(&self, other: &*mut T) -> bool { *self < *other }
2846 fn le(&self, other: &*mut T) -> bool { *self <= *other }
2849 fn gt(&self, other: &*mut T) -> bool { *self > *other }
2852 fn ge(&self, other: &*mut T) -> bool { *self >= *other }