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 /// [`ptr::read`]: ../ptr/fn.read.html
107 /// Behavior is undefined if any of the following conditions are violated:
109 /// * `to_drop` must be [valid] for reads.
111 /// * `to_drop` must be properly aligned. See the example below for how to drop
112 /// an unaligned pointer.
114 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
115 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
116 /// foo` counts as a use because it will cause the value to be dropped
117 /// again. [`write`] can be used to overwrite data without causing it to be
120 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
122 /// [valid]: ../ptr/index.html#safety
123 /// [`Copy`]: ../marker/trait.Copy.html
124 /// [`write`]: ../ptr/fn.write.html
128 /// Manually remove the last item from a vector:
134 /// let last = Rc::new(1);
135 /// let weak = Rc::downgrade(&last);
137 /// let mut v = vec![Rc::new(0), last];
140 /// // Get a raw pointer to the last element in `v`.
141 /// let ptr = &mut v[1] as *mut _;
142 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
143 /// // to prevent issues if the `drop_in_place` below panics.
145 /// // Without a call `drop_in_place`, the last item would never be dropped,
146 /// // and the memory it manages would be leaked.
147 /// ptr::drop_in_place(ptr);
150 /// assert_eq!(v, &[0.into()]);
152 /// // Ensure that the last item was dropped.
153 /// assert!(weak.upgrade().is_none());
156 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
160 /// use std::mem::{self, MaybeUninit};
162 /// unsafe fn drop_after_copy<T>(to_drop: *mut T) {
163 /// let mut copy: MaybeUninit<T> = MaybeUninit::uninit();
164 /// ptr::copy(to_drop, copy.as_mut_ptr(), 1);
165 /// drop(copy.assume_init());
168 /// #[repr(packed, C)]
171 /// unaligned: Vec<i32>,
174 /// let mut p = Packed { _padding: 0, unaligned: vec![42] };
176 /// drop_after_copy(&mut p.unaligned as *mut _);
181 /// Notice that the compiler performs this copy automatically when dropping packed structs,
182 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
184 #[stable(feature = "drop_in_place", since = "1.8.0")]
186 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
187 real_drop_in_place(&mut *to_drop)
190 // The real `drop_in_place` -- the one that gets called implicitly when variables go
191 // out of scope -- should have a safe reference and not a raw pointer as argument
192 // type. When we drop a local variable, we access it with a pointer that behaves
193 // like a safe reference; transmuting that to a raw pointer does not mean we can
194 // actually access it with raw pointers.
195 #[lang = "drop_in_place"]
196 #[allow(unconditional_recursion)]
197 unsafe fn real_drop_in_place<T: ?Sized>(to_drop: &mut T) {
198 // Code here does not matter - this is replaced by the
199 // real drop glue by the compiler.
200 real_drop_in_place(to_drop)
203 /// Creates a null raw pointer.
210 /// let p: *const i32 = ptr::null();
211 /// assert!(p.is_null());
214 #[stable(feature = "rust1", since = "1.0.0")]
216 pub const fn null<T>() -> *const T { 0 as *const T }
218 /// Creates a null mutable raw pointer.
225 /// let p: *mut i32 = ptr::null_mut();
226 /// assert!(p.is_null());
229 #[stable(feature = "rust1", since = "1.0.0")]
231 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
234 pub(crate) union Repr<T> {
235 pub(crate) rust: *const [T],
237 pub(crate) raw: FatPtr<T>,
241 pub(crate) struct FatPtr<T> {
243 pub(crate) len: usize,
246 /// Forms a slice from a pointer and a length.
248 /// The `len` argument is the number of **elements**, not the number of bytes.
253 /// #![feature(slice_from_raw_parts)]
256 /// // create a slice pointer when starting out with a pointer to the first element
257 /// let mut x = [5, 6, 7];
258 /// let ptr = &mut x[0] as *mut _;
259 /// let slice = ptr::slice_from_raw_parts_mut(ptr, 3);
260 /// assert_eq!(unsafe { &*slice }[2], 7);
263 #[unstable(feature = "slice_from_raw_parts", reason = "recently added", issue = "36925")]
264 pub fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
265 unsafe { Repr { raw: FatPtr { data, len } }.rust }
268 /// Performs the same functionality as [`from_raw_parts`], except that a
269 /// mutable slice is returned.
271 /// See the documentation of [`from_raw_parts`] for more details.
273 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
275 #[unstable(feature = "slice_from_raw_parts", reason = "recently added", issue = "36925")]
276 pub fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
277 unsafe { Repr { raw: FatPtr { data, len } }.rust_mut }
280 /// Swaps the values at two mutable locations of the same type, without
281 /// deinitializing either.
283 /// But for the following two exceptions, this function is semantically
284 /// equivalent to [`mem::swap`]:
286 /// * It operates on raw pointers instead of references. When references are
287 /// available, [`mem::swap`] should be preferred.
289 /// * The two pointed-to values may overlap. If the values do overlap, then the
290 /// overlapping region of memory from `x` will be used. This is demonstrated
291 /// in the second example below.
293 /// [`mem::swap`]: ../mem/fn.swap.html
297 /// Behavior is undefined if any of the following conditions are violated:
299 /// * Both `x` and `y` must be [valid] for reads and writes.
301 /// * Both `x` and `y` must be properly aligned.
303 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
305 /// [valid]: ../ptr/index.html#safety
309 /// Swapping two non-overlapping regions:
314 /// let mut array = [0, 1, 2, 3];
316 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
317 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
321 /// assert_eq!([2, 3, 0, 1], array);
325 /// Swapping two overlapping regions:
330 /// let mut array = [0, 1, 2, 3];
332 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
333 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
337 /// // The indices `1..3` of the slice overlap between `x` and `y`.
338 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
339 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
340 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
341 /// // This implementation is defined to make the latter choice.
342 /// assert_eq!([1, 0, 1, 2], array);
346 #[stable(feature = "rust1", since = "1.0.0")]
347 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
348 // Give ourselves some scratch space to work with.
349 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
350 let mut tmp = MaybeUninit::<T>::uninit();
353 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
354 copy(y, x, 1); // `x` and `y` may overlap
355 copy_nonoverlapping(tmp.as_ptr(), y, 1);
358 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
359 /// beginning at `x` and `y`. The two regions must *not* overlap.
363 /// Behavior is undefined if any of the following conditions are violated:
365 /// * Both `x` and `y` must be [valid] for reads and writes of `count *
366 /// size_of::<T>()` bytes.
368 /// * Both `x` and `y` must be properly aligned.
370 /// * The region of memory beginning at `x` with a size of `count *
371 /// size_of::<T>()` bytes must *not* overlap with the region of memory
372 /// beginning at `y` with the same size.
374 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
375 /// the pointers must be non-NULL and properly aligned.
377 /// [valid]: ../ptr/index.html#safety
386 /// let mut x = [1, 2, 3, 4];
387 /// let mut y = [7, 8, 9];
390 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
393 /// assert_eq!(x, [7, 8, 3, 4]);
394 /// assert_eq!(y, [1, 2, 9]);
397 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
398 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
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 writes.
483 /// * `dst` must be properly aligned.
485 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
487 /// [valid]: ../ptr/index.html#safety
494 /// let mut rust = vec!['b', 'u', 's', 't'];
496 /// // `mem::replace` would have the same effect without requiring the unsafe
499 /// ptr::replace(&mut rust[0], 'r')
502 /// assert_eq!(b, 'b');
503 /// assert_eq!(rust, &['r', 'u', 's', 't']);
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
508 mem::swap(&mut *dst, &mut src); // cannot overlap
512 /// Reads the value from `src` without moving it. This leaves the
513 /// memory in `src` unchanged.
517 /// Behavior is undefined if any of the following conditions are violated:
519 /// * `src` must be [valid] for reads.
521 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
524 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
532 /// let y = &x as *const i32;
535 /// assert_eq!(std::ptr::read(y), 12);
539 /// Manually implement [`mem::swap`]:
544 /// fn swap<T>(a: &mut T, b: &mut T) {
546 /// // Create a bitwise copy of the value at `a` in `tmp`.
547 /// let tmp = ptr::read(a);
549 /// // Exiting at this point (either by explicitly returning or by
550 /// // calling a function which panics) would cause the value in `tmp` to
551 /// // be dropped while the same value is still referenced by `a`. This
552 /// // could trigger undefined behavior if `T` is not `Copy`.
554 /// // Create a bitwise copy of the value at `b` in `a`.
555 /// // This is safe because mutable references cannot alias.
556 /// ptr::copy_nonoverlapping(b, a, 1);
558 /// // As above, exiting here could trigger undefined behavior because
559 /// // the same value is referenced by `a` and `b`.
561 /// // Move `tmp` into `b`.
562 /// ptr::write(b, tmp);
564 /// // `tmp` has been moved (`write` takes ownership of its second argument),
565 /// // so nothing is dropped implicitly here.
569 /// let mut foo = "foo".to_owned();
570 /// let mut bar = "bar".to_owned();
572 /// swap(&mut foo, &mut bar);
574 /// assert_eq!(foo, "bar");
575 /// assert_eq!(bar, "foo");
578 /// ## Ownership of the Returned Value
580 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
581 /// If `T` is not [`Copy`], using both the returned value and the value at
582 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
583 /// use because it will attempt to drop the value at `*src`.
585 /// [`write`] can be used to overwrite data without causing it to be dropped.
590 /// let mut s = String::from("foo");
592 /// // `s2` now points to the same underlying memory as `s`.
593 /// let mut s2: String = ptr::read(&s);
595 /// assert_eq!(s2, "foo");
597 /// // Assigning to `s2` causes its original value to be dropped. Beyond
598 /// // this point, `s` must no longer be used, as the underlying memory has
600 /// s2 = String::default();
601 /// assert_eq!(s2, "");
603 /// // Assigning to `s` would cause the old value to be dropped again,
604 /// // resulting in undefined behavior.
605 /// // s = String::from("bar"); // ERROR
607 /// // `ptr::write` can be used to overwrite a value without dropping it.
608 /// ptr::write(&mut s, String::from("bar"));
611 /// assert_eq!(s, "bar");
614 /// [`mem::swap`]: ../mem/fn.swap.html
615 /// [valid]: ../ptr/index.html#safety
616 /// [`Copy`]: ../marker/trait.Copy.html
617 /// [`read_unaligned`]: ./fn.read_unaligned.html
618 /// [`write`]: ./fn.write.html
620 #[stable(feature = "rust1", since = "1.0.0")]
621 pub unsafe fn read<T>(src: *const T) -> T {
622 let mut tmp = MaybeUninit::<T>::uninit();
623 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
627 /// Reads the value from `src` without moving it. This leaves the
628 /// memory in `src` unchanged.
630 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
634 /// Behavior is undefined if any of the following conditions are violated:
636 /// * `src` must be [valid] for reads.
638 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
639 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
640 /// value and the value at `*src` can [violate memory safety][read-ownership].
642 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
644 /// [`Copy`]: ../marker/trait.Copy.html
645 /// [`read`]: ./fn.read.html
646 /// [`write_unaligned`]: ./fn.write_unaligned.html
647 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
648 /// [valid]: ../ptr/index.html#safety
652 /// Access members of a packed struct by reference:
657 /// #[repr(packed, C)]
665 /// unaligned: 0x01020304,
669 /// // Take the address of a 32-bit integer which is not aligned.
670 /// // This must be done as a raw pointer; unaligned references are invalid.
671 /// let unaligned = &x.unaligned as *const u32;
673 /// // Dereferencing normally will emit an aligned load instruction,
674 /// // causing undefined behavior.
675 /// // let v = *unaligned; // ERROR
677 /// // Instead, use `read_unaligned` to read improperly aligned values.
678 /// let v = ptr::read_unaligned(unaligned);
683 /// // Accessing unaligned values directly is safe.
684 /// assert!(x.unaligned == v);
687 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
688 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
689 let mut tmp = MaybeUninit::<T>::uninit();
690 copy_nonoverlapping(src as *const u8,
691 tmp.as_mut_ptr() as *mut u8,
692 mem::size_of::<T>());
696 /// Overwrites a memory location with the given value without reading or
697 /// dropping the old value.
699 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
700 /// allocations or resources, so care should be taken not to overwrite an object
701 /// that should be dropped.
703 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
704 /// location pointed to by `dst`.
706 /// This is appropriate for initializing uninitialized memory, or overwriting
707 /// memory that has previously been [`read`] from.
709 /// [`read`]: ./fn.read.html
713 /// Behavior is undefined if any of the following conditions are violated:
715 /// * `dst` must be [valid] for writes.
717 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
720 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
722 /// [valid]: ../ptr/index.html#safety
723 /// [`write_unaligned`]: ./fn.write_unaligned.html
731 /// let y = &mut x as *mut i32;
735 /// std::ptr::write(y, z);
736 /// assert_eq!(std::ptr::read(y), 12);
740 /// Manually implement [`mem::swap`]:
745 /// fn swap<T>(a: &mut T, b: &mut T) {
747 /// // Create a bitwise copy of the value at `a` in `tmp`.
748 /// let tmp = ptr::read(a);
750 /// // Exiting at this point (either by explicitly returning or by
751 /// // calling a function which panics) would cause the value in `tmp` to
752 /// // be dropped while the same value is still referenced by `a`. This
753 /// // could trigger undefined behavior if `T` is not `Copy`.
755 /// // Create a bitwise copy of the value at `b` in `a`.
756 /// // This is safe because mutable references cannot alias.
757 /// ptr::copy_nonoverlapping(b, a, 1);
759 /// // As above, exiting here could trigger undefined behavior because
760 /// // the same value is referenced by `a` and `b`.
762 /// // Move `tmp` into `b`.
763 /// ptr::write(b, tmp);
765 /// // `tmp` has been moved (`write` takes ownership of its second argument),
766 /// // so nothing is dropped implicitly here.
770 /// let mut foo = "foo".to_owned();
771 /// let mut bar = "bar".to_owned();
773 /// swap(&mut foo, &mut bar);
775 /// assert_eq!(foo, "bar");
776 /// assert_eq!(bar, "foo");
779 /// [`mem::swap`]: ../mem/fn.swap.html
781 #[stable(feature = "rust1", since = "1.0.0")]
782 pub unsafe fn write<T>(dst: *mut T, src: T) {
783 intrinsics::move_val_init(&mut *dst, src)
786 /// Overwrites a memory location with the given value without reading or
787 /// dropping the old value.
789 /// Unlike [`write`], the pointer may be unaligned.
791 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
792 /// could leak allocations or resources, so care should be taken not to overwrite
793 /// an object that should be dropped.
795 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
796 /// location pointed to by `dst`.
798 /// This is appropriate for initializing uninitialized memory, or overwriting
799 /// memory that has previously been read with [`read_unaligned`].
801 /// [`write`]: ./fn.write.html
802 /// [`read_unaligned`]: ./fn.read_unaligned.html
806 /// Behavior is undefined if any of the following conditions are violated:
808 /// * `dst` must be [valid] for writes.
810 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
812 /// [valid]: ../ptr/index.html#safety
816 /// Access fields in a packed struct:
819 /// use std::{mem, ptr};
821 /// #[repr(packed, C)]
822 /// #[derive(Default)]
828 /// let v = 0x01020304;
829 /// let mut x: Packed = unsafe { mem::zeroed() };
832 /// // Take a reference to a 32-bit integer which is not aligned.
833 /// let unaligned = &mut x.unaligned as *mut u32;
835 /// // Dereferencing normally will emit an aligned store instruction,
836 /// // causing undefined behavior because the pointer is not aligned.
837 /// // *unaligned = v; // ERROR
839 /// // Instead, use `write_unaligned` to write improperly aligned values.
840 /// ptr::write_unaligned(unaligned, v);
843 /// // Accessing unaligned values directly is safe.
844 /// assert!(x.unaligned == v);
847 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
848 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
849 copy_nonoverlapping(&src as *const T as *const u8,
851 mem::size_of::<T>());
855 /// Performs a volatile read of the value from `src` without moving it. This
856 /// leaves the memory in `src` unchanged.
858 /// Volatile operations are intended to act on I/O memory, and are guaranteed
859 /// to not be elided or reordered by the compiler across other volatile
862 /// [`write_volatile`]: ./fn.write_volatile.html
866 /// Rust does not currently have a rigorously and formally defined memory model,
867 /// so the precise semantics of what "volatile" means here is subject to change
868 /// over time. That being said, the semantics will almost always end up pretty
869 /// similar to [C11's definition of volatile][c11].
871 /// The compiler shouldn't change the relative order or number of volatile
872 /// memory operations. However, volatile memory operations on zero-sized types
873 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
874 /// and may be ignored.
876 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
880 /// Behavior is undefined if any of the following conditions are violated:
882 /// * `src` must be [valid] for reads.
884 /// * `src` must be properly aligned.
886 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
887 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
888 /// value and the value at `*src` can [violate memory safety][read-ownership].
889 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
892 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
894 /// [valid]: ../ptr/index.html#safety
895 /// [`Copy`]: ../marker/trait.Copy.html
896 /// [`read`]: ./fn.read.html
897 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
899 /// Just like in C, whether an operation is volatile has no bearing whatsoever
900 /// on questions involving concurrent access from multiple threads. Volatile
901 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
902 /// a race between a `read_volatile` and any write operation to the same location
903 /// is undefined behavior.
911 /// let y = &x as *const i32;
914 /// assert_eq!(std::ptr::read_volatile(y), 12);
918 #[stable(feature = "volatile", since = "1.9.0")]
919 pub unsafe fn read_volatile<T>(src: *const T) -> T {
920 intrinsics::volatile_load(src)
923 /// Performs a volatile write of a memory location with the given value without
924 /// reading or dropping the old value.
926 /// Volatile operations are intended to act on I/O memory, and are guaranteed
927 /// to not be elided or reordered by the compiler across other volatile
930 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
931 /// could leak allocations or resources, so care should be taken not to overwrite
932 /// an object that should be dropped.
934 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
935 /// location pointed to by `dst`.
937 /// [`read_volatile`]: ./fn.read_volatile.html
941 /// Rust does not currently have a rigorously and formally defined memory model,
942 /// so the precise semantics of what "volatile" means here is subject to change
943 /// over time. That being said, the semantics will almost always end up pretty
944 /// similar to [C11's definition of volatile][c11].
946 /// The compiler shouldn't change the relative order or number of volatile
947 /// memory operations. However, volatile memory operations on zero-sized types
948 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
949 /// and may be ignored.
951 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
955 /// Behavior is undefined if any of the following conditions are violated:
957 /// * `dst` must be [valid] for writes.
959 /// * `dst` must be properly aligned.
961 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
963 /// [valid]: ../ptr/index.html#safety
965 /// Just like in C, whether an operation is volatile has no bearing whatsoever
966 /// on questions involving concurrent access from multiple threads. Volatile
967 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
968 /// a race between a `write_volatile` and any other operation (reading or writing)
969 /// on the same location is undefined behavior.
977 /// let y = &mut x as *mut i32;
981 /// std::ptr::write_volatile(y, z);
982 /// assert_eq!(std::ptr::read_volatile(y), 12);
986 #[stable(feature = "volatile", since = "1.9.0")]
987 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
988 intrinsics::volatile_store(dst, src);
991 #[lang = "const_ptr"]
992 impl<T: ?Sized> *const T {
993 /// Returns `true` if the pointer is null.
995 /// Note that unsized types have many possible null pointers, as only the
996 /// raw data pointer is considered, not their length, vtable, etc.
997 /// Therefore, two pointers that are null may still not compare equal to
1005 /// let s: &str = "Follow the rabbit";
1006 /// let ptr: *const u8 = s.as_ptr();
1007 /// assert!(!ptr.is_null());
1009 #[stable(feature = "rust1", since = "1.0.0")]
1011 pub fn is_null(self) -> bool {
1012 // Compare via a cast to a thin pointer, so fat pointers are only
1013 // considering their "data" part for null-ness.
1014 (self as *const u8) == null()
1017 /// Cast to a pointer to a different type
1018 #[unstable(feature = "ptr_cast", issue = "60602")]
1020 pub const fn cast<U>(self) -> *const U {
1024 /// Returns `None` if the pointer is null, or else returns a reference to
1025 /// the value wrapped in `Some`.
1029 /// While this method and its mutable counterpart are useful for
1030 /// null-safety, it is important to note that this is still an unsafe
1031 /// operation because the returned value could be pointing to invalid
1034 /// When calling this method, you have to ensure that if the pointer is
1035 /// non-NULL, then it is properly aligned, dereferencable (for the whole
1036 /// size of `T`) and points to an initialized instance of `T`. This applies
1037 /// even if the result of this method is unused!
1038 /// (The part about being initialized is not yet fully decided, but until
1039 /// it is, the only safe approach is to ensure that they are indeed initialized.)
1041 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1042 /// not necessarily reflect the actual lifetime of the data. It is up to the
1043 /// caller to ensure that for the duration of this lifetime, the memory this
1044 /// pointer points to does not get written to outside of `UnsafeCell<U>`.
1051 /// let ptr: *const u8 = &10u8 as *const u8;
1054 /// if let Some(val_back) = ptr.as_ref() {
1055 /// println!("We got back the value: {}!", val_back);
1060 /// # Null-unchecked version
1062 /// If you are sure the pointer can never be null and are looking for some kind of
1063 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1064 /// dereference the pointer directly.
1067 /// let ptr: *const u8 = &10u8 as *const u8;
1070 /// let val_back = &*ptr;
1071 /// println!("We got back the value: {}!", val_back);
1074 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1076 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1084 /// Calculates the offset from a pointer.
1086 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1087 /// offset of `3 * size_of::<T>()` bytes.
1091 /// If any of the following conditions are violated, the result is Undefined
1094 /// * Both the starting and resulting pointer must be either in bounds or one
1095 /// byte past the end of the same allocated object.
1097 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1099 /// * The offset being in bounds cannot rely on "wrapping around" the address
1100 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1102 /// The compiler and standard library generally tries to ensure allocations
1103 /// never reach a size where an offset is a concern. For instance, `Vec`
1104 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1105 /// `vec.as_ptr().add(vec.len())` is always safe.
1107 /// Most platforms fundamentally can't even construct such an allocation.
1108 /// For instance, no known 64-bit platform can ever serve a request
1109 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1110 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1111 /// more than `isize::MAX` bytes with things like Physical Address
1112 /// Extension. As such, memory acquired directly from allocators or memory
1113 /// mapped files *may* be too large to handle with this function.
1115 /// Consider using `wrapping_offset` instead if these constraints are
1116 /// difficult to satisfy. The only advantage of this method is that it
1117 /// enables more aggressive compiler optimizations.
1124 /// let s: &str = "123";
1125 /// let ptr: *const u8 = s.as_ptr();
1128 /// println!("{}", *ptr.offset(1) as char);
1129 /// println!("{}", *ptr.offset(2) as char);
1132 #[stable(feature = "rust1", since = "1.0.0")]
1134 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
1135 intrinsics::offset(self, count)
1138 /// Calculates the offset from a pointer using wrapping arithmetic.
1140 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1141 /// offset of `3 * size_of::<T>()` bytes.
1145 /// The resulting pointer does not need to be in bounds, but it is
1146 /// potentially hazardous to dereference (which requires `unsafe`).
1147 /// In particular, the resulting pointer may *not* be used to access a
1148 /// different allocated object than the one `self` points to. In other
1149 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1150 /// *not* the same as `y`, and dereferencing it is undefined behavior
1151 /// unless `x` and `y` point into the same allocated object.
1153 /// Always use `.offset(count)` instead when possible, because `offset`
1154 /// allows the compiler to optimize better. If you need to cross object
1155 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1162 /// // Iterate using a raw pointer in increments of two elements
1163 /// let data = [1u8, 2, 3, 4, 5];
1164 /// let mut ptr: *const u8 = data.as_ptr();
1166 /// let end_rounded_up = ptr.wrapping_offset(6);
1168 /// // This loop prints "1, 3, 5, "
1169 /// while ptr != end_rounded_up {
1171 /// print!("{}, ", *ptr);
1173 /// ptr = ptr.wrapping_offset(step);
1176 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1178 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
1180 intrinsics::arith_offset(self, count)
1184 /// Calculates the distance between two pointers. The returned value is in
1185 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1187 /// This function is the inverse of [`offset`].
1189 /// [`offset`]: #method.offset
1190 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
1194 /// If any of the following conditions are violated, the result is Undefined
1197 /// * Both the starting and other pointer must be either in bounds or one
1198 /// byte past the end of the same allocated object.
1200 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1202 /// * The distance between the pointers, in bytes, must be an exact multiple
1203 /// of the size of `T`.
1205 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1207 /// The compiler and standard library generally try to ensure allocations
1208 /// never reach a size where an offset is a concern. For instance, `Vec`
1209 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1210 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1212 /// Most platforms fundamentally can't even construct such an allocation.
1213 /// For instance, no known 64-bit platform can ever serve a request
1214 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1215 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1216 /// more than `isize::MAX` bytes with things like Physical Address
1217 /// Extension. As such, memory acquired directly from allocators or memory
1218 /// mapped files *may* be too large to handle with this function.
1220 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1221 /// difficult to satisfy. The only advantage of this method is that it
1222 /// enables more aggressive compiler optimizations.
1226 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1233 /// #![feature(ptr_offset_from)]
1236 /// let ptr1: *const i32 = &a[1];
1237 /// let ptr2: *const i32 = &a[3];
1239 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1240 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1241 /// assert_eq!(ptr1.offset(2), ptr2);
1242 /// assert_eq!(ptr2.offset(-2), ptr1);
1245 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1247 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1248 let pointee_size = mem::size_of::<T>();
1249 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1251 // This is the same sequence that Clang emits for pointer subtraction.
1252 // It can be neither `nsw` nor `nuw` because the input is treated as
1253 // unsigned but then the output is treated as signed, so neither works.
1254 let d = isize::wrapping_sub(self as _, origin as _);
1255 intrinsics::exact_div(d, pointee_size as _)
1258 /// Calculates the distance between two pointers. The returned value is in
1259 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1261 /// If the address different between the two pointers is not a multiple of
1262 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1265 /// Though this method is safe for any two pointers, note that its result
1266 /// will be mostly useless if the two pointers aren't into the same allocated
1267 /// object, for example if they point to two different local variables.
1271 /// This function panics if `T` is a zero-sized type.
1278 /// #![feature(ptr_wrapping_offset_from)]
1281 /// let ptr1: *const i32 = &a[1];
1282 /// let ptr2: *const i32 = &a[3];
1283 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1284 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1285 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1286 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1288 /// let ptr1: *const i32 = 3 as _;
1289 /// let ptr2: *const i32 = 13 as _;
1290 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1292 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1294 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1295 let pointee_size = mem::size_of::<T>();
1296 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1298 let d = isize::wrapping_sub(self as _, origin as _);
1299 d.wrapping_div(pointee_size as _)
1302 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1304 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1305 /// offset of `3 * size_of::<T>()` bytes.
1309 /// If any of the following conditions are violated, the result is Undefined
1312 /// * Both the starting and resulting pointer must be either in bounds or one
1313 /// byte past the end of the same allocated object.
1315 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1317 /// * The offset being in bounds cannot rely on "wrapping around" the address
1318 /// space. That is, the infinite-precision sum must fit in a `usize`.
1320 /// The compiler and standard library generally tries to ensure allocations
1321 /// never reach a size where an offset is a concern. For instance, `Vec`
1322 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1323 /// `vec.as_ptr().add(vec.len())` is always safe.
1325 /// Most platforms fundamentally can't even construct such an allocation.
1326 /// For instance, no known 64-bit platform can ever serve a request
1327 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1328 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1329 /// more than `isize::MAX` bytes with things like Physical Address
1330 /// Extension. As such, memory acquired directly from allocators or memory
1331 /// mapped files *may* be too large to handle with this function.
1333 /// Consider using `wrapping_offset` instead if these constraints are
1334 /// difficult to satisfy. The only advantage of this method is that it
1335 /// enables more aggressive compiler optimizations.
1342 /// let s: &str = "123";
1343 /// let ptr: *const u8 = s.as_ptr();
1346 /// println!("{}", *ptr.add(1) as char);
1347 /// println!("{}", *ptr.add(2) as char);
1350 #[stable(feature = "pointer_methods", since = "1.26.0")]
1352 pub unsafe fn add(self, count: usize) -> Self
1355 self.offset(count as isize)
1358 /// Calculates the offset from a pointer (convenience for
1359 /// `.offset((count as isize).wrapping_neg())`).
1361 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1362 /// offset of `3 * size_of::<T>()` bytes.
1366 /// If any of the following conditions are violated, the result is Undefined
1369 /// * Both the starting and resulting pointer must be either in bounds or one
1370 /// byte past the end of the same allocated object.
1372 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1374 /// * The offset being in bounds cannot rely on "wrapping around" the address
1375 /// space. That is, the infinite-precision sum must fit in a usize.
1377 /// The compiler and standard library generally tries to ensure allocations
1378 /// never reach a size where an offset is a concern. For instance, `Vec`
1379 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1380 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1382 /// Most platforms fundamentally can't even construct such an allocation.
1383 /// For instance, no known 64-bit platform can ever serve a request
1384 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1385 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1386 /// more than `isize::MAX` bytes with things like Physical Address
1387 /// Extension. As such, memory acquired directly from allocators or memory
1388 /// mapped files *may* be too large to handle with this function.
1390 /// Consider using `wrapping_offset` instead if these constraints are
1391 /// difficult to satisfy. The only advantage of this method is that it
1392 /// enables more aggressive compiler optimizations.
1399 /// let s: &str = "123";
1402 /// let end: *const u8 = s.as_ptr().add(3);
1403 /// println!("{}", *end.sub(1) as char);
1404 /// println!("{}", *end.sub(2) as char);
1407 #[stable(feature = "pointer_methods", since = "1.26.0")]
1409 pub unsafe fn sub(self, count: usize) -> Self
1412 self.offset((count as isize).wrapping_neg())
1415 /// Calculates the offset from a pointer using wrapping arithmetic.
1416 /// (convenience for `.wrapping_offset(count as isize)`)
1418 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1419 /// offset of `3 * size_of::<T>()` bytes.
1423 /// The resulting pointer does not need to be in bounds, but it is
1424 /// potentially hazardous to dereference (which requires `unsafe`).
1426 /// Always use `.add(count)` instead when possible, because `add`
1427 /// allows the compiler to optimize better.
1434 /// // Iterate using a raw pointer in increments of two elements
1435 /// let data = [1u8, 2, 3, 4, 5];
1436 /// let mut ptr: *const u8 = data.as_ptr();
1438 /// let end_rounded_up = ptr.wrapping_add(6);
1440 /// // This loop prints "1, 3, 5, "
1441 /// while ptr != end_rounded_up {
1443 /// print!("{}, ", *ptr);
1445 /// ptr = ptr.wrapping_add(step);
1448 #[stable(feature = "pointer_methods", since = "1.26.0")]
1450 pub fn wrapping_add(self, count: usize) -> Self
1453 self.wrapping_offset(count as isize)
1456 /// Calculates the offset from a pointer using wrapping arithmetic.
1457 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1459 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1460 /// offset of `3 * size_of::<T>()` bytes.
1464 /// The resulting pointer does not need to be in bounds, but it is
1465 /// potentially hazardous to dereference (which requires `unsafe`).
1467 /// Always use `.sub(count)` instead when possible, because `sub`
1468 /// allows the compiler to optimize better.
1475 /// // Iterate using a raw pointer in increments of two elements (backwards)
1476 /// let data = [1u8, 2, 3, 4, 5];
1477 /// let mut ptr: *const u8 = data.as_ptr();
1478 /// let start_rounded_down = ptr.wrapping_sub(2);
1479 /// ptr = ptr.wrapping_add(4);
1481 /// // This loop prints "5, 3, 1, "
1482 /// while ptr != start_rounded_down {
1484 /// print!("{}, ", *ptr);
1486 /// ptr = ptr.wrapping_sub(step);
1489 #[stable(feature = "pointer_methods", since = "1.26.0")]
1491 pub fn wrapping_sub(self, count: usize) -> Self
1494 self.wrapping_offset((count as isize).wrapping_neg())
1497 /// Reads the value from `self` without moving it. This leaves the
1498 /// memory in `self` unchanged.
1500 /// See [`ptr::read`] for safety concerns and examples.
1502 /// [`ptr::read`]: ./ptr/fn.read.html
1503 #[stable(feature = "pointer_methods", since = "1.26.0")]
1505 pub unsafe fn read(self) -> T
1511 /// Performs a volatile read of the value from `self` without moving it. This
1512 /// leaves the memory in `self` unchanged.
1514 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1515 /// to not be elided or reordered by the compiler across other volatile
1518 /// See [`ptr::read_volatile`] for safety concerns and examples.
1520 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
1521 #[stable(feature = "pointer_methods", since = "1.26.0")]
1523 pub unsafe fn read_volatile(self) -> T
1529 /// Reads the value from `self` without moving it. This leaves the
1530 /// memory in `self` unchanged.
1532 /// Unlike `read`, the pointer may be unaligned.
1534 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1536 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
1537 #[stable(feature = "pointer_methods", since = "1.26.0")]
1539 pub unsafe fn read_unaligned(self) -> T
1542 read_unaligned(self)
1545 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1546 /// and destination may overlap.
1548 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1550 /// See [`ptr::copy`] for safety concerns and examples.
1552 /// [`ptr::copy`]: ./ptr/fn.copy.html
1553 #[stable(feature = "pointer_methods", since = "1.26.0")]
1555 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1558 copy(self, dest, count)
1561 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1562 /// and destination may *not* overlap.
1564 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1566 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1568 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
1569 #[stable(feature = "pointer_methods", since = "1.26.0")]
1571 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1574 copy_nonoverlapping(self, dest, count)
1577 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1580 /// If it is not possible to align the pointer, the implementation returns
1581 /// `usize::max_value()`.
1583 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1584 /// used with the `offset` or `offset_to` methods.
1586 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
1587 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1588 /// the returned offset is correct in all terms other than alignment.
1592 /// The function panics if `align` is not a power-of-two.
1596 /// Accessing adjacent `u8` as `u16`
1599 /// # fn foo(n: usize) {
1600 /// # use std::mem::align_of;
1602 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1603 /// let ptr = &x[n] as *const u8;
1604 /// let offset = ptr.align_offset(align_of::<u16>());
1605 /// if offset < x.len() - n - 1 {
1606 /// let u16_ptr = ptr.add(offset) as *const u16;
1607 /// assert_ne!(*u16_ptr, 500);
1609 /// // while the pointer can be aligned via `offset`, it would point
1610 /// // outside the allocation
1614 #[stable(feature = "align_offset", since = "1.36.0")]
1615 pub fn align_offset(self, align: usize) -> usize where T: Sized {
1616 if !align.is_power_of_two() {
1617 panic!("align_offset: align is not a power-of-two");
1620 align_offset(self, align)
1627 impl<T: ?Sized> *mut T {
1628 /// Returns `true` if the pointer is null.
1630 /// Note that unsized types have many possible null pointers, as only the
1631 /// raw data pointer is considered, not their length, vtable, etc.
1632 /// Therefore, two pointers that are null may still not compare equal to
1640 /// let mut s = [1, 2, 3];
1641 /// let ptr: *mut u32 = s.as_mut_ptr();
1642 /// assert!(!ptr.is_null());
1644 #[stable(feature = "rust1", since = "1.0.0")]
1646 pub fn is_null(self) -> bool {
1647 // Compare via a cast to a thin pointer, so fat pointers are only
1648 // considering their "data" part for null-ness.
1649 (self as *mut u8) == null_mut()
1652 /// Cast to a pointer to a different type
1653 #[unstable(feature = "ptr_cast", issue = "60602")]
1655 pub const fn cast<U>(self) -> *mut U {
1659 /// Returns `None` if the pointer is null, or else returns a reference to
1660 /// the value wrapped in `Some`.
1664 /// While this method and its mutable counterpart are useful for
1665 /// null-safety, it is important to note that this is still an unsafe
1666 /// operation because the returned value could be pointing to invalid
1669 /// When calling this method, you have to ensure that if the pointer is
1670 /// non-NULL, then it is properly aligned, dereferencable (for the whole
1671 /// size of `T`) and points to an initialized instance of `T`. This applies
1672 /// even if the result of this method is unused!
1673 /// (The part about being initialized is not yet fully decided, but until
1674 /// it is, the only safe approach is to ensure that they are indeed initialized.)
1676 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1677 /// not necessarily reflect the actual lifetime of the data. It is up to the
1678 /// caller to ensure that for the duration of this lifetime, the memory this
1679 /// pointer points to does not get written to outside of `UnsafeCell<U>`.
1686 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1689 /// if let Some(val_back) = ptr.as_ref() {
1690 /// println!("We got back the value: {}!", val_back);
1695 /// # Null-unchecked version
1697 /// If you are sure the pointer can never be null and are looking for some kind of
1698 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1699 /// dereference the pointer directly.
1702 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1705 /// let val_back = &*ptr;
1706 /// println!("We got back the value: {}!", val_back);
1709 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1711 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1719 /// Calculates the offset from a pointer.
1721 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1722 /// offset of `3 * size_of::<T>()` bytes.
1726 /// If any of the following conditions are violated, the result is Undefined
1729 /// * Both the starting and resulting pointer must be either in bounds or one
1730 /// byte past the end of the same allocated object.
1732 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1734 /// * The offset being in bounds cannot rely on "wrapping around" the address
1735 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1737 /// The compiler and standard library generally tries to ensure allocations
1738 /// never reach a size where an offset is a concern. For instance, `Vec`
1739 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1740 /// `vec.as_ptr().add(vec.len())` is always safe.
1742 /// Most platforms fundamentally can't even construct such an allocation.
1743 /// For instance, no known 64-bit platform can ever serve a request
1744 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1745 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1746 /// more than `isize::MAX` bytes with things like Physical Address
1747 /// Extension. As such, memory acquired directly from allocators or memory
1748 /// mapped files *may* be too large to handle with this function.
1750 /// Consider using `wrapping_offset` instead if these constraints are
1751 /// difficult to satisfy. The only advantage of this method is that it
1752 /// enables more aggressive compiler optimizations.
1759 /// let mut s = [1, 2, 3];
1760 /// let ptr: *mut u32 = s.as_mut_ptr();
1763 /// println!("{}", *ptr.offset(1));
1764 /// println!("{}", *ptr.offset(2));
1767 #[stable(feature = "rust1", since = "1.0.0")]
1769 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1770 intrinsics::offset(self, count) as *mut T
1773 /// Calculates the offset from a pointer using wrapping arithmetic.
1774 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1775 /// offset of `3 * size_of::<T>()` bytes.
1779 /// The resulting pointer does not need to be in bounds, but it is
1780 /// potentially hazardous to dereference (which requires `unsafe`).
1781 /// In particular, the resulting pointer may *not* be used to access a
1782 /// different allocated object than the one `self` points to. In other
1783 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1784 /// *not* the same as `y`, and dereferencing it is undefined behavior
1785 /// unless `x` and `y` point into the same allocated object.
1787 /// Always use `.offset(count)` instead when possible, because `offset`
1788 /// allows the compiler to optimize better. If you need to cross object
1789 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1796 /// // Iterate using a raw pointer in increments of two elements
1797 /// let mut data = [1u8, 2, 3, 4, 5];
1798 /// let mut ptr: *mut u8 = data.as_mut_ptr();
1800 /// let end_rounded_up = ptr.wrapping_offset(6);
1802 /// while ptr != end_rounded_up {
1806 /// ptr = ptr.wrapping_offset(step);
1808 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1810 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1812 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1814 intrinsics::arith_offset(self, count) as *mut T
1818 /// Returns `None` if the pointer is null, or else returns a mutable
1819 /// reference to the value wrapped in `Some`.
1823 /// As with [`as_ref`], this is unsafe because it cannot verify the validity
1824 /// of the returned pointer, nor can it ensure that the lifetime `'a`
1825 /// returned is indeed a valid lifetime for the contained data.
1827 /// When calling this method, you have to ensure that if the pointer is
1828 /// non-NULL, then it is properly aligned, dereferencable (for the whole
1829 /// size of `T`) and points to an initialized instance of `T`. This applies
1830 /// even if the result of this method is unused!
1831 /// (The part about being initialized is not yet fully decided, but until
1832 /// it is the only safe approach is to ensure that they are indeed initialized.)
1834 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1835 /// not necessarily reflect the actual lifetime of the data. It is up to the
1836 /// caller to ensure that for the duration of this lifetime, the memory this
1837 /// pointer points to does not get accessed through any other pointer.
1839 /// [`as_ref`]: #method.as_ref
1846 /// let mut s = [1, 2, 3];
1847 /// let ptr: *mut u32 = s.as_mut_ptr();
1848 /// let first_value = unsafe { ptr.as_mut().unwrap() };
1849 /// *first_value = 4;
1850 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1852 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1854 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1862 /// Calculates the distance between two pointers. The returned value is in
1863 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1865 /// This function is the inverse of [`offset`].
1867 /// [`offset`]: #method.offset-1
1868 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
1872 /// If any of the following conditions are violated, the result is Undefined
1875 /// * Both the starting and other pointer must be either in bounds or one
1876 /// byte past the end of the same allocated object.
1878 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1880 /// * The distance between the pointers, in bytes, must be an exact multiple
1881 /// of the size of `T`.
1883 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1885 /// The compiler and standard library generally try to ensure allocations
1886 /// never reach a size where an offset is a concern. For instance, `Vec`
1887 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1888 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1890 /// Most platforms fundamentally can't even construct such an allocation.
1891 /// For instance, no known 64-bit platform can ever serve a request
1892 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1893 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1894 /// more than `isize::MAX` bytes with things like Physical Address
1895 /// Extension. As such, memory acquired directly from allocators or memory
1896 /// mapped files *may* be too large to handle with this function.
1898 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1899 /// difficult to satisfy. The only advantage of this method is that it
1900 /// enables more aggressive compiler optimizations.
1904 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1911 /// #![feature(ptr_offset_from)]
1913 /// let mut a = [0; 5];
1914 /// let ptr1: *mut i32 = &mut a[1];
1915 /// let ptr2: *mut i32 = &mut a[3];
1917 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1918 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1919 /// assert_eq!(ptr1.offset(2), ptr2);
1920 /// assert_eq!(ptr2.offset(-2), ptr1);
1923 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1925 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1926 (self as *const T).offset_from(origin)
1929 /// Calculates the distance between two pointers. The returned value is in
1930 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1932 /// If the address different between the two pointers is not a multiple of
1933 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1936 /// Though this method is safe for any two pointers, note that its result
1937 /// will be mostly useless if the two pointers aren't into the same allocated
1938 /// object, for example if they point to two different local variables.
1942 /// This function panics if `T` is a zero-sized type.
1949 /// #![feature(ptr_wrapping_offset_from)]
1951 /// let mut a = [0; 5];
1952 /// let ptr1: *mut i32 = &mut a[1];
1953 /// let ptr2: *mut i32 = &mut a[3];
1954 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1955 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1956 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1957 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1959 /// let ptr1: *mut i32 = 3 as _;
1960 /// let ptr2: *mut i32 = 13 as _;
1961 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1963 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1965 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1966 (self as *const T).wrapping_offset_from(origin)
1969 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1971 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1972 /// offset of `3 * size_of::<T>()` bytes.
1976 /// If any of the following conditions are violated, the result is Undefined
1979 /// * Both the starting and resulting pointer must be either in bounds or one
1980 /// byte past the end of the same allocated object.
1982 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1984 /// * The offset being in bounds cannot rely on "wrapping around" the address
1985 /// space. That is, the infinite-precision sum must fit in a `usize`.
1987 /// The compiler and standard library generally tries to ensure allocations
1988 /// never reach a size where an offset is a concern. For instance, `Vec`
1989 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1990 /// `vec.as_ptr().add(vec.len())` is always safe.
1992 /// Most platforms fundamentally can't even construct such an allocation.
1993 /// For instance, no known 64-bit platform can ever serve a request
1994 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1995 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1996 /// more than `isize::MAX` bytes with things like Physical Address
1997 /// Extension. As such, memory acquired directly from allocators or memory
1998 /// mapped files *may* be too large to handle with this function.
2000 /// Consider using `wrapping_offset` instead if these constraints are
2001 /// difficult to satisfy. The only advantage of this method is that it
2002 /// enables more aggressive compiler optimizations.
2009 /// let s: &str = "123";
2010 /// let ptr: *const u8 = s.as_ptr();
2013 /// println!("{}", *ptr.add(1) as char);
2014 /// println!("{}", *ptr.add(2) as char);
2017 #[stable(feature = "pointer_methods", since = "1.26.0")]
2019 pub unsafe fn add(self, count: usize) -> Self
2022 self.offset(count as isize)
2025 /// Calculates the offset from a pointer (convenience for
2026 /// `.offset((count as isize).wrapping_neg())`).
2028 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2029 /// offset of `3 * size_of::<T>()` bytes.
2033 /// If any of the following conditions are violated, the result is Undefined
2036 /// * Both the starting and resulting pointer must be either in bounds or one
2037 /// byte past the end of the same allocated object.
2039 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
2041 /// * The offset being in bounds cannot rely on "wrapping around" the address
2042 /// space. That is, the infinite-precision sum must fit in a usize.
2044 /// The compiler and standard library generally tries to ensure allocations
2045 /// never reach a size where an offset is a concern. For instance, `Vec`
2046 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
2047 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
2049 /// Most platforms fundamentally can't even construct such an allocation.
2050 /// For instance, no known 64-bit platform can ever serve a request
2051 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
2052 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
2053 /// more than `isize::MAX` bytes with things like Physical Address
2054 /// Extension. As such, memory acquired directly from allocators or memory
2055 /// mapped files *may* be too large to handle with this function.
2057 /// Consider using `wrapping_offset` instead if these constraints are
2058 /// difficult to satisfy. The only advantage of this method is that it
2059 /// enables more aggressive compiler optimizations.
2066 /// let s: &str = "123";
2069 /// let end: *const u8 = s.as_ptr().add(3);
2070 /// println!("{}", *end.sub(1) as char);
2071 /// println!("{}", *end.sub(2) as char);
2074 #[stable(feature = "pointer_methods", since = "1.26.0")]
2076 pub unsafe fn sub(self, count: usize) -> Self
2079 self.offset((count as isize).wrapping_neg())
2082 /// Calculates the offset from a pointer using wrapping arithmetic.
2083 /// (convenience for `.wrapping_offset(count as isize)`)
2085 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2086 /// offset of `3 * size_of::<T>()` bytes.
2090 /// The resulting pointer does not need to be in bounds, but it is
2091 /// potentially hazardous to dereference (which requires `unsafe`).
2093 /// Always use `.add(count)` instead when possible, because `add`
2094 /// allows the compiler to optimize better.
2101 /// // Iterate using a raw pointer in increments of two elements
2102 /// let data = [1u8, 2, 3, 4, 5];
2103 /// let mut ptr: *const u8 = data.as_ptr();
2105 /// let end_rounded_up = ptr.wrapping_add(6);
2107 /// // This loop prints "1, 3, 5, "
2108 /// while ptr != end_rounded_up {
2110 /// print!("{}, ", *ptr);
2112 /// ptr = ptr.wrapping_add(step);
2115 #[stable(feature = "pointer_methods", since = "1.26.0")]
2117 pub fn wrapping_add(self, count: usize) -> Self
2120 self.wrapping_offset(count as isize)
2123 /// Calculates the offset from a pointer using wrapping arithmetic.
2124 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
2126 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2127 /// offset of `3 * size_of::<T>()` bytes.
2131 /// The resulting pointer does not need to be in bounds, but it is
2132 /// potentially hazardous to dereference (which requires `unsafe`).
2134 /// Always use `.sub(count)` instead when possible, because `sub`
2135 /// allows the compiler to optimize better.
2142 /// // Iterate using a raw pointer in increments of two elements (backwards)
2143 /// let data = [1u8, 2, 3, 4, 5];
2144 /// let mut ptr: *const u8 = data.as_ptr();
2145 /// let start_rounded_down = ptr.wrapping_sub(2);
2146 /// ptr = ptr.wrapping_add(4);
2148 /// // This loop prints "5, 3, 1, "
2149 /// while ptr != start_rounded_down {
2151 /// print!("{}, ", *ptr);
2153 /// ptr = ptr.wrapping_sub(step);
2156 #[stable(feature = "pointer_methods", since = "1.26.0")]
2158 pub fn wrapping_sub(self, count: usize) -> Self
2161 self.wrapping_offset((count as isize).wrapping_neg())
2164 /// Reads the value from `self` without moving it. This leaves the
2165 /// memory in `self` unchanged.
2167 /// See [`ptr::read`] for safety concerns and examples.
2169 /// [`ptr::read`]: ./ptr/fn.read.html
2170 #[stable(feature = "pointer_methods", since = "1.26.0")]
2172 pub unsafe fn read(self) -> T
2178 /// Performs a volatile read of the value from `self` without moving it. This
2179 /// leaves the memory in `self` unchanged.
2181 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2182 /// to not be elided or reordered by the compiler across other volatile
2185 /// See [`ptr::read_volatile`] for safety concerns and examples.
2187 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
2188 #[stable(feature = "pointer_methods", since = "1.26.0")]
2190 pub unsafe fn read_volatile(self) -> T
2196 /// Reads the value from `self` without moving it. This leaves the
2197 /// memory in `self` unchanged.
2199 /// Unlike `read`, the pointer may be unaligned.
2201 /// See [`ptr::read_unaligned`] for safety concerns and examples.
2203 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
2204 #[stable(feature = "pointer_methods", since = "1.26.0")]
2206 pub unsafe fn read_unaligned(self) -> T
2209 read_unaligned(self)
2212 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2213 /// and destination may overlap.
2215 /// NOTE: this has the *same* argument order as [`ptr::copy`].
2217 /// See [`ptr::copy`] for safety concerns and examples.
2219 /// [`ptr::copy`]: ./ptr/fn.copy.html
2220 #[stable(feature = "pointer_methods", since = "1.26.0")]
2222 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
2225 copy(self, dest, count)
2228 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2229 /// and destination may *not* overlap.
2231 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
2233 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2235 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2236 #[stable(feature = "pointer_methods", since = "1.26.0")]
2238 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
2241 copy_nonoverlapping(self, dest, count)
2244 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2245 /// and destination may overlap.
2247 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
2249 /// See [`ptr::copy`] for safety concerns and examples.
2251 /// [`ptr::copy`]: ./ptr/fn.copy.html
2252 #[stable(feature = "pointer_methods", since = "1.26.0")]
2254 pub unsafe fn copy_from(self, src: *const T, count: usize)
2257 copy(src, self, count)
2260 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2261 /// and destination may *not* overlap.
2263 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
2265 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2267 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2268 #[stable(feature = "pointer_methods", since = "1.26.0")]
2270 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
2273 copy_nonoverlapping(src, self, count)
2276 /// Executes the destructor (if any) of the pointed-to value.
2278 /// See [`ptr::drop_in_place`] for safety concerns and examples.
2280 /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
2281 #[stable(feature = "pointer_methods", since = "1.26.0")]
2283 pub unsafe fn drop_in_place(self) {
2287 /// Overwrites a memory location with the given value without reading or
2288 /// dropping the old value.
2290 /// See [`ptr::write`] for safety concerns and examples.
2292 /// [`ptr::write`]: ./ptr/fn.write.html
2293 #[stable(feature = "pointer_methods", since = "1.26.0")]
2295 pub unsafe fn write(self, val: T)
2301 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
2302 /// bytes of memory starting at `self` to `val`.
2304 /// See [`ptr::write_bytes`] for safety concerns and examples.
2306 /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
2307 #[stable(feature = "pointer_methods", since = "1.26.0")]
2309 pub unsafe fn write_bytes(self, val: u8, count: usize)
2312 write_bytes(self, val, count)
2315 /// Performs a volatile write of a memory location with the given value without
2316 /// reading or dropping the old value.
2318 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2319 /// to not be elided or reordered by the compiler across other volatile
2322 /// See [`ptr::write_volatile`] for safety concerns and examples.
2324 /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
2325 #[stable(feature = "pointer_methods", since = "1.26.0")]
2327 pub unsafe fn write_volatile(self, val: T)
2330 write_volatile(self, val)
2333 /// Overwrites a memory location with the given value without reading or
2334 /// dropping the old value.
2336 /// Unlike `write`, the pointer may be unaligned.
2338 /// See [`ptr::write_unaligned`] for safety concerns and examples.
2340 /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
2341 #[stable(feature = "pointer_methods", since = "1.26.0")]
2343 pub unsafe fn write_unaligned(self, val: T)
2346 write_unaligned(self, val)
2349 /// Replaces the value at `self` with `src`, returning the old
2350 /// value, without dropping either.
2352 /// See [`ptr::replace`] for safety concerns and examples.
2354 /// [`ptr::replace`]: ./ptr/fn.replace.html
2355 #[stable(feature = "pointer_methods", since = "1.26.0")]
2357 pub unsafe fn replace(self, src: T) -> T
2363 /// Swaps the values at two mutable locations of the same type, without
2364 /// deinitializing either. They may overlap, unlike `mem::swap` which is
2365 /// otherwise equivalent.
2367 /// See [`ptr::swap`] for safety concerns and examples.
2369 /// [`ptr::swap`]: ./ptr/fn.swap.html
2370 #[stable(feature = "pointer_methods", since = "1.26.0")]
2372 pub unsafe fn swap(self, with: *mut T)
2378 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
2381 /// If it is not possible to align the pointer, the implementation returns
2382 /// `usize::max_value()`.
2384 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
2385 /// used with the `offset` or `offset_to` methods.
2387 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
2388 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
2389 /// the returned offset is correct in all terms other than alignment.
2393 /// The function panics if `align` is not a power-of-two.
2397 /// Accessing adjacent `u8` as `u16`
2400 /// # fn foo(n: usize) {
2401 /// # use std::mem::align_of;
2403 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
2404 /// let ptr = &x[n] as *const u8;
2405 /// let offset = ptr.align_offset(align_of::<u16>());
2406 /// if offset < x.len() - n - 1 {
2407 /// let u16_ptr = ptr.add(offset) as *const u16;
2408 /// assert_ne!(*u16_ptr, 500);
2410 /// // while the pointer can be aligned via `offset`, it would point
2411 /// // outside the allocation
2415 #[stable(feature = "align_offset", since = "1.36.0")]
2416 pub fn align_offset(self, align: usize) -> usize where T: Sized {
2417 if !align.is_power_of_two() {
2418 panic!("align_offset: align is not a power-of-two");
2421 align_offset(self, align)
2426 /// Align pointer `p`.
2428 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
2429 /// to pointer `p` so that pointer `p` would get aligned to `a`.
2431 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
2432 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2435 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2436 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2437 /// than trying to adapt this to accommodate that change.
2439 /// Any questions go to @nagisa.
2440 #[lang="align_offset"]
2441 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2442 /// Calculate multiplicative modular inverse of `x` modulo `m`.
2444 /// This implementation is tailored for align_offset and has following preconditions:
2446 /// * `m` is a power-of-two;
2447 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2449 /// Implementation of this function shall not panic. Ever.
2451 fn mod_inv(x: usize, m: usize) -> usize {
2452 /// Multiplicative modular inverse table modulo 2⁴ = 16.
2454 /// Note, that this table does not contain values where inverse does not exist (i.e., for
2455 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2456 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2457 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2458 const INV_TABLE_MOD: usize = 16;
2460 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
2462 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
2463 if m <= INV_TABLE_MOD {
2464 table_inverse & (m - 1)
2466 // We iterate "up" using the following formula:
2468 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2470 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
2471 let mut inverse = table_inverse;
2472 let mut going_mod = INV_TABLE_MOD_SQUARED;
2474 // y = y * (2 - xy) mod n
2476 // Note, that we use wrapping operations here intentionally – the original formula
2477 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
2478 // usize::max_value()` instead, because we take the result `mod n` at the end
2480 inverse = inverse.wrapping_mul(
2481 2usize.wrapping_sub(x.wrapping_mul(inverse))
2482 ) & (going_mod - 1);
2484 return inverse & (m - 1);
2486 going_mod = going_mod.wrapping_mul(going_mod);
2491 let stride = mem::size_of::<T>();
2492 let a_minus_one = a.wrapping_sub(1);
2493 let pmoda = p as usize & a_minus_one;
2496 // Already aligned. Yay!
2501 return if stride == 0 {
2502 // If the pointer is not aligned, and the element is zero-sized, then no amount of
2503 // elements will ever align the pointer.
2506 a.wrapping_sub(pmoda)
2510 let smoda = stride & a_minus_one;
2511 // a is power-of-two so cannot be 0. stride = 0 is handled above.
2512 let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
2513 let gcd = 1usize << gcdpow;
2515 if p as usize & (gcd - 1) == 0 {
2516 // This branch solves for the following linear congruence equation:
2518 // $$ p + so ≡ 0 mod a $$
2520 // $p$ here is the pointer value, $s$ – stride of `T`, $o$ offset in `T`s, and $a$ – the
2521 // requested alignment.
2524 // o = (a - (p mod a))/g * ((s/g)⁻¹ mod a)
2526 // The first term is “the relative alignment of p to a”, the second term is “how does
2527 // incrementing p by s bytes change the relative alignment of p”. Division by `g` is
2528 // necessary to make this equation well formed if $a$ and $s$ are not co-prime.
2530 // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
2531 // to take the result $o mod lcm(s, a)$. We can replace $lcm(s, a)$ with just a $a / g$.
2532 let j = a.wrapping_sub(pmoda) >> gcdpow;
2533 let k = smoda >> gcdpow;
2534 return intrinsics::unchecked_rem(j.wrapping_mul(mod_inv(k, a)), a >> gcdpow);
2537 // Cannot be aligned at all.
2543 // Equality for pointers
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 impl<T: ?Sized> PartialEq for *const T {
2547 fn eq(&self, other: &*const T) -> bool { *self == *other }
2550 #[stable(feature = "rust1", since = "1.0.0")]
2551 impl<T: ?Sized> Eq for *const T {}
2553 #[stable(feature = "rust1", since = "1.0.0")]
2554 impl<T: ?Sized> PartialEq for *mut T {
2556 fn eq(&self, other: &*mut T) -> bool { *self == *other }
2559 #[stable(feature = "rust1", since = "1.0.0")]
2560 impl<T: ?Sized> Eq for *mut T {}
2562 /// Compares raw pointers for equality.
2564 /// This is the same as using the `==` operator, but less generic:
2565 /// the arguments have to be `*const T` raw pointers,
2566 /// not anything that implements `PartialEq`.
2568 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2569 /// by their address rather than comparing the values they point to
2570 /// (which is what the `PartialEq for &T` implementation does).
2578 /// let other_five = 5;
2579 /// let five_ref = &five;
2580 /// let same_five_ref = &five;
2581 /// let other_five_ref = &other_five;
2583 /// assert!(five_ref == same_five_ref);
2584 /// assert!(ptr::eq(five_ref, same_five_ref));
2586 /// assert!(five_ref == other_five_ref);
2587 /// assert!(!ptr::eq(five_ref, other_five_ref));
2590 /// Slices are also compared by their length (fat pointers):
2593 /// let a = [1, 2, 3];
2594 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
2595 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
2596 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
2599 /// Traits are also compared by their implementation:
2602 /// #[repr(transparent)]
2603 /// struct Wrapper { member: i32 }
2606 /// impl Trait for Wrapper {}
2607 /// impl Trait for i32 {}
2610 /// let wrapper = Wrapper { member: 10 };
2612 /// // Pointers have equal addresses.
2613 /// assert!(std::ptr::eq(
2614 /// &wrapper as *const Wrapper as *const u8,
2615 /// &wrapper.member as *const i32 as *const u8
2618 /// // Objects have equal addresses, but `Trait` has different implementations.
2619 /// assert!(!std::ptr::eq(
2620 /// &wrapper as &dyn Trait,
2621 /// &wrapper.member as &dyn Trait,
2623 /// assert!(!std::ptr::eq(
2624 /// &wrapper as &dyn Trait as *const dyn Trait,
2625 /// &wrapper.member as &dyn Trait as *const dyn Trait,
2628 /// // Converting the reference to a `*const u8` compares by address.
2629 /// assert!(std::ptr::eq(
2630 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
2631 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
2635 #[stable(feature = "ptr_eq", since = "1.17.0")]
2637 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2641 /// Hash a raw pointer.
2643 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
2644 /// by its address rather than the value it points to
2645 /// (which is what the `Hash for &T` implementation does).
2650 /// use std::collections::hash_map::DefaultHasher;
2651 /// use std::hash::{Hash, Hasher};
2655 /// let five_ref = &five;
2657 /// let mut hasher = DefaultHasher::new();
2658 /// ptr::hash(five_ref, &mut hasher);
2659 /// let actual = hasher.finish();
2661 /// let mut hasher = DefaultHasher::new();
2662 /// (five_ref as *const i32).hash(&mut hasher);
2663 /// let expected = hasher.finish();
2665 /// assert_eq!(actual, expected);
2667 #[stable(feature = "ptr_hash", since = "1.35.0")]
2668 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
2669 use crate::hash::Hash;
2673 // Impls for function pointers
2674 macro_rules! fnptr_impls_safety_abi {
2675 ($FnTy: ty, $($Arg: ident),*) => {
2676 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2677 impl<Ret, $($Arg),*> PartialEq for $FnTy {
2679 fn eq(&self, other: &Self) -> bool {
2680 *self as usize == *other as usize
2684 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2685 impl<Ret, $($Arg),*> Eq for $FnTy {}
2687 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2688 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2690 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2691 (*self as usize).partial_cmp(&(*other as usize))
2695 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2696 impl<Ret, $($Arg),*> Ord for $FnTy {
2698 fn cmp(&self, other: &Self) -> Ordering {
2699 (*self as usize).cmp(&(*other as usize))
2703 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2704 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2705 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2706 state.write_usize(*self as usize)
2710 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2711 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2712 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2713 fmt::Pointer::fmt(&(*self as *const ()), f)
2717 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2718 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2719 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2720 fmt::Pointer::fmt(&(*self as *const ()), f)
2726 macro_rules! fnptr_impls_args {
2727 ($($Arg: ident),+) => {
2728 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
2729 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
2730 fnptr_impls_safety_abi! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
2731 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
2732 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
2733 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
2736 // No variadic functions with 0 parameters
2737 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2738 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2739 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2740 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2744 fnptr_impls_args! { }
2745 fnptr_impls_args! { A }
2746 fnptr_impls_args! { A, B }
2747 fnptr_impls_args! { A, B, C }
2748 fnptr_impls_args! { A, B, C, D }
2749 fnptr_impls_args! { A, B, C, D, E }
2750 fnptr_impls_args! { A, B, C, D, E, F }
2751 fnptr_impls_args! { A, B, C, D, E, F, G }
2752 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2753 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2754 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2755 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2756 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2758 // Comparison for pointers
2759 #[stable(feature = "rust1", since = "1.0.0")]
2760 impl<T: ?Sized> Ord for *const T {
2762 fn cmp(&self, other: &*const T) -> Ordering {
2765 } else if self == other {
2773 #[stable(feature = "rust1", since = "1.0.0")]
2774 impl<T: ?Sized> PartialOrd for *const T {
2776 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2777 Some(self.cmp(other))
2781 fn lt(&self, other: &*const T) -> bool { *self < *other }
2784 fn le(&self, other: &*const T) -> bool { *self <= *other }
2787 fn gt(&self, other: &*const T) -> bool { *self > *other }
2790 fn ge(&self, other: &*const T) -> bool { *self >= *other }
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<T: ?Sized> Ord for *mut T {
2796 fn cmp(&self, other: &*mut T) -> Ordering {
2799 } else if self == other {
2807 #[stable(feature = "rust1", since = "1.0.0")]
2808 impl<T: ?Sized> PartialOrd for *mut T {
2810 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2811 Some(self.cmp(other))
2815 fn lt(&self, other: &*mut T) -> bool { *self < *other }
2818 fn le(&self, other: &*mut T) -> bool { *self <= *other }
2821 fn gt(&self, other: &*mut T) -> bool { *self > *other }
2824 fn ge(&self, other: &*mut T) -> bool { *self >= *other }