1 // ignore-tidy-filelength
3 //! Manually manage memory through raw pointers.
5 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
9 //! Many functions in this module take raw pointers as arguments and read from
10 //! or write to them. For this to be safe, these pointers must be *valid*.
11 //! Whether a pointer is valid depends on the operation it is used for
12 //! (read or write), and the extent of the memory that is accessed (i.e.,
13 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
14 //! to access only a single value, in which case the documentation omits the size
15 //! and implicitly assumes it to be `size_of::<T>()` bytes.
17 //! The precise rules for validity are not determined yet. The guarantees that are
18 //! provided at this point are very minimal:
20 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
21 //! * All pointers (except for the null pointer) are valid for all operations of
23 //! * All accesses performed by functions in this module are *non-atomic* in the sense
24 //! of [atomic operations] used to synchronize between threads. This means it is
25 //! undefined behavior to perform two concurrent accesses to the same location from different
26 //! threads unless both accesses only read from memory. Notice that this explicitly
27 //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
28 //! be used for inter-thread synchronization.
29 //! * The result of casting a reference to a pointer is valid for as long as the
30 //! underlying object is live and no reference (just raw pointers) is used to
31 //! access the same memory.
33 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
34 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
35 //! will be provided eventually, as the [aliasing] rules are being determined. For more
36 //! information, see the [book] as well as the section in the reference devoted
37 //! to [undefined behavior][ub].
41 //! Valid raw pointers as defined above are not necessarily properly aligned (where
42 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
43 //! aligned to `mem::align_of::<T>()`). However, most functions require their
44 //! arguments to be properly aligned, and will explicitly state
45 //! this requirement in their documentation. Notable exceptions to this are
46 //! [`read_unaligned`] and [`write_unaligned`].
48 //! When a function requires proper alignment, it does so even if the access
49 //! has size 0, i.e., even if memory is not actually touched. Consider using
50 //! [`NonNull::dangling`] in such cases.
52 //! [aliasing]: ../../nomicon/aliasing.html
53 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
54 //! [ub]: ../../reference/behavior-considered-undefined.html
55 //! [null]: ./fn.null.html
56 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
57 //! [atomic operations]: ../../std/sync/atomic/index.html
58 //! [`copy`]: ../../std/ptr/fn.copy.html
59 //! [`offset`]: ../../std/primitive.pointer.html#method.offset
60 //! [`read_unaligned`]: ./fn.read_unaligned.html
61 //! [`write_unaligned`]: ./fn.write_unaligned.html
62 //! [`read_volatile`]: ./fn.read_volatile.html
63 //! [`write_volatile`]: ./fn.write_volatile.html
64 //! [`NonNull::dangling`]: ./struct.NonNull.html#method.dangling
66 #![stable(feature = "rust1", since = "1.0.0")]
68 use crate::convert::From;
69 use crate::intrinsics;
70 use crate::ops::{CoerceUnsized, DispatchFromDyn};
73 use crate::marker::{PhantomData, Unsize};
74 use crate::mem::{self, MaybeUninit};
76 use crate::cmp::Ordering::{self, Less, Equal, Greater};
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use crate::intrinsics::copy_nonoverlapping;
81 #[stable(feature = "rust1", since = "1.0.0")]
82 pub use crate::intrinsics::copy;
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub use crate::intrinsics::write_bytes;
87 /// Executes the destructor (if any) of the pointed-to value.
89 /// This is semantically equivalent to calling [`ptr::read`] and discarding
90 /// the result, but has the following advantages:
92 /// * It is *required* to use `drop_in_place` to drop unsized types like
93 /// trait objects, because they can't be read out onto the stack and
96 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
97 /// dropping manually allocated memory (e.g., when writing Box/Rc/Vec),
98 /// as the compiler doesn't need to prove that it's sound to elide the
101 /// [`ptr::read`]: ../ptr/fn.read.html
105 /// Behavior is undefined if any of the following conditions are violated:
107 /// * `to_drop` must be [valid] for reads.
109 /// * `to_drop` must be properly aligned. See the example below for how to drop
110 /// an unaligned pointer.
112 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
113 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
114 /// foo` counts as a use because it will cause the value to be dropped
115 /// again. [`write`] can be used to overwrite data without causing it to be
118 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
120 /// [valid]: ../ptr/index.html#safety
121 /// [`Copy`]: ../marker/trait.Copy.html
122 /// [`write`]: ../ptr/fn.write.html
126 /// Manually remove the last item from a vector:
132 /// let last = Rc::new(1);
133 /// let weak = Rc::downgrade(&last);
135 /// let mut v = vec![Rc::new(0), last];
138 /// // Get a raw pointer to the last element in `v`.
139 /// let ptr = &mut v[1] as *mut _;
140 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
141 /// // to prevent issues if the `drop_in_place` below panics.
143 /// // Without a call `drop_in_place`, the last item would never be dropped,
144 /// // and the memory it manages would be leaked.
145 /// ptr::drop_in_place(ptr);
148 /// assert_eq!(v, &[0.into()]);
150 /// // Ensure that the last item was dropped.
151 /// assert!(weak.upgrade().is_none());
154 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
160 /// unsafe fn drop_after_copy<T>(to_drop: *mut T) {
161 /// let mut copy: T = mem::uninitialized();
162 /// ptr::copy(to_drop, &mut copy, 1);
166 /// #[repr(packed, C)]
169 /// unaligned: Vec<i32>,
172 /// let mut p = Packed { _padding: 0, unaligned: vec![42] };
174 /// drop_after_copy(&mut p.unaligned as *mut _);
179 /// Notice that the compiler performs this copy automatically when dropping packed structs,
180 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
182 #[stable(feature = "drop_in_place", since = "1.8.0")]
184 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
185 real_drop_in_place(&mut *to_drop)
188 // The real `drop_in_place` -- the one that gets called implicitly when variables go
189 // out of scope -- should have a safe reference and not a raw pointer as argument
190 // type. When we drop a local variable, we access it with a pointer that behaves
191 // like a safe reference; transmuting that to a raw pointer does not mean we can
192 // actually access it with raw pointers.
193 #[lang = "drop_in_place"]
194 #[allow(unconditional_recursion)]
195 unsafe fn real_drop_in_place<T: ?Sized>(to_drop: &mut T) {
196 // Code here does not matter - this is replaced by the
197 // real drop glue by the compiler.
198 real_drop_in_place(to_drop)
201 /// Creates a null raw pointer.
208 /// let p: *const i32 = ptr::null();
209 /// assert!(p.is_null());
212 #[stable(feature = "rust1", since = "1.0.0")]
214 pub const fn null<T>() -> *const T { 0 as *const T }
216 /// Creates a null mutable raw pointer.
223 /// let p: *mut i32 = ptr::null_mut();
224 /// assert!(p.is_null());
227 #[stable(feature = "rust1", since = "1.0.0")]
229 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
231 /// Swaps the values at two mutable locations of the same type, without
232 /// deinitializing either.
234 /// But for the following two exceptions, this function is semantically
235 /// equivalent to [`mem::swap`]:
237 /// * It operates on raw pointers instead of references. When references are
238 /// available, [`mem::swap`] should be preferred.
240 /// * The two pointed-to values may overlap. If the values do overlap, then the
241 /// overlapping region of memory from `x` will be used. This is demonstrated
242 /// in the second example below.
244 /// [`mem::swap`]: ../mem/fn.swap.html
248 /// Behavior is undefined if any of the following conditions are violated:
250 /// * Both `x` and `y` must be [valid] for reads and writes.
252 /// * Both `x` and `y` must be properly aligned.
254 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
256 /// [valid]: ../ptr/index.html#safety
260 /// Swapping two non-overlapping regions:
265 /// let mut array = [0, 1, 2, 3];
267 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
268 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
272 /// assert_eq!([2, 3, 0, 1], array);
276 /// Swapping two overlapping regions:
281 /// let mut array = [0, 1, 2, 3];
283 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
284 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
288 /// // The indices `1..3` of the slice overlap between `x` and `y`.
289 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
290 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
291 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
292 /// // This implementation is defined to make the latter choice.
293 /// assert_eq!([1, 0, 1, 2], array);
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
299 // Give ourselves some scratch space to work with.
300 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
301 let mut tmp = MaybeUninit::<T>::uninit();
304 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
305 copy(y, x, 1); // `x` and `y` may overlap
306 copy_nonoverlapping(tmp.as_ptr(), y, 1);
309 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
310 /// beginning at `x` and `y`. The two regions must *not* overlap.
314 /// Behavior is undefined if any of the following conditions are violated:
316 /// * Both `x` and `y` must be [valid] for reads and writes of `count *
317 /// size_of::<T>()` bytes.
319 /// * Both `x` and `y` must be properly aligned.
321 /// * The region of memory beginning at `x` with a size of `count *
322 /// size_of::<T>()` bytes must *not* overlap with the region of memory
323 /// beginning at `y` with the same size.
325 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
326 /// the pointers must be non-NULL and properly aligned.
328 /// [valid]: ../ptr/index.html#safety
337 /// let mut x = [1, 2, 3, 4];
338 /// let mut y = [7, 8, 9];
341 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
344 /// assert_eq!(x, [7, 8, 3, 4]);
345 /// assert_eq!(y, [1, 2, 9]);
348 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
349 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
350 let x = x as *mut u8;
351 let y = y as *mut u8;
352 let len = mem::size_of::<T>() * count;
353 swap_nonoverlapping_bytes(x, y, len)
357 pub(crate) unsafe fn swap_nonoverlapping_one<T>(x: *mut T, y: *mut T) {
358 // For types smaller than the block optimization below,
359 // just swap directly to avoid pessimizing codegen.
360 if mem::size_of::<T>() < 32 {
362 copy_nonoverlapping(y, x, 1);
365 swap_nonoverlapping(x, y, 1);
370 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
371 // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
372 // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
373 // Haswell E processors. LLVM is more able to optimize if we give a struct a
374 // #[repr(simd)], even if we don't actually use this struct directly.
376 // FIXME repr(simd) broken on emscripten and redox
377 // It's also broken on big-endian powerpc64 and s390x. #42778
378 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox",
379 target_endian = "big")),
381 struct Block(u64, u64, u64, u64);
382 struct UnalignedBlock(u64, u64, u64, u64);
384 let block_size = mem::size_of::<Block>();
386 // Loop through x & y, copying them `Block` at a time
387 // The optimizer should unroll the loop fully for most types
388 // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
390 while i + block_size <= len {
391 // Create some uninitialized memory as scratch space
392 // Declaring `t` here avoids aligning the stack when this loop is unused
393 let mut t = mem::MaybeUninit::<Block>::uninit();
394 let t = t.as_mut_ptr() as *mut u8;
398 // Swap a block of bytes of x & y, using t as a temporary buffer
399 // This should be optimized into efficient SIMD operations where available
400 copy_nonoverlapping(x, t, block_size);
401 copy_nonoverlapping(y, x, block_size);
402 copy_nonoverlapping(t, y, block_size);
407 // Swap any remaining bytes
408 let mut t = mem::MaybeUninit::<UnalignedBlock>::uninit();
411 let t = t.as_mut_ptr() as *mut u8;
415 copy_nonoverlapping(x, t, rem);
416 copy_nonoverlapping(y, x, rem);
417 copy_nonoverlapping(t, y, rem);
421 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
423 /// Neither value is dropped.
425 /// This function is semantically equivalent to [`mem::replace`] except that it
426 /// operates on raw pointers instead of references. When references are
427 /// available, [`mem::replace`] should be preferred.
429 /// [`mem::replace`]: ../mem/fn.replace.html
433 /// Behavior is undefined if any of the following conditions are violated:
435 /// * `dst` must be [valid] for writes.
437 /// * `dst` must be properly aligned.
439 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
441 /// [valid]: ../ptr/index.html#safety
448 /// let mut rust = vec!['b', 'u', 's', 't'];
450 /// // `mem::replace` would have the same effect without requiring the unsafe
453 /// ptr::replace(&mut rust[0], 'r')
456 /// assert_eq!(b, 'b');
457 /// assert_eq!(rust, &['r', 'u', 's', 't']);
460 #[stable(feature = "rust1", since = "1.0.0")]
461 pub unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
462 mem::swap(&mut *dst, &mut src); // cannot overlap
466 /// Reads the value from `src` without moving it. This leaves the
467 /// memory in `src` unchanged.
471 /// Behavior is undefined if any of the following conditions are violated:
473 /// * `src` must be [valid] for reads.
475 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
478 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
486 /// let y = &x as *const i32;
489 /// assert_eq!(std::ptr::read(y), 12);
493 /// Manually implement [`mem::swap`]:
498 /// fn swap<T>(a: &mut T, b: &mut T) {
500 /// // Create a bitwise copy of the value at `a` in `tmp`.
501 /// let tmp = ptr::read(a);
503 /// // Exiting at this point (either by explicitly returning or by
504 /// // calling a function which panics) would cause the value in `tmp` to
505 /// // be dropped while the same value is still referenced by `a`. This
506 /// // could trigger undefined behavior if `T` is not `Copy`.
508 /// // Create a bitwise copy of the value at `b` in `a`.
509 /// // This is safe because mutable references cannot alias.
510 /// ptr::copy_nonoverlapping(b, a, 1);
512 /// // As above, exiting here could trigger undefined behavior because
513 /// // the same value is referenced by `a` and `b`.
515 /// // Move `tmp` into `b`.
516 /// ptr::write(b, tmp);
518 /// // `tmp` has been moved (`write` takes ownership of its second argument),
519 /// // so nothing is dropped implicitly here.
523 /// let mut foo = "foo".to_owned();
524 /// let mut bar = "bar".to_owned();
526 /// swap(&mut foo, &mut bar);
528 /// assert_eq!(foo, "bar");
529 /// assert_eq!(bar, "foo");
532 /// ## Ownership of the Returned Value
534 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
535 /// If `T` is not [`Copy`], using both the returned value and the value at
536 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
537 /// use because it will attempt to drop the value at `*src`.
539 /// [`write`] can be used to overwrite data without causing it to be dropped.
544 /// let mut s = String::from("foo");
546 /// // `s2` now points to the same underlying memory as `s`.
547 /// let mut s2: String = ptr::read(&s);
549 /// assert_eq!(s2, "foo");
551 /// // Assigning to `s2` causes its original value to be dropped. Beyond
552 /// // this point, `s` must no longer be used, as the underlying memory has
554 /// s2 = String::default();
555 /// assert_eq!(s2, "");
557 /// // Assigning to `s` would cause the old value to be dropped again,
558 /// // resulting in undefined behavior.
559 /// // s = String::from("bar"); // ERROR
561 /// // `ptr::write` can be used to overwrite a value without dropping it.
562 /// ptr::write(&mut s, String::from("bar"));
565 /// assert_eq!(s, "bar");
568 /// [`mem::swap`]: ../mem/fn.swap.html
569 /// [valid]: ../ptr/index.html#safety
570 /// [`Copy`]: ../marker/trait.Copy.html
571 /// [`read_unaligned`]: ./fn.read_unaligned.html
572 /// [`write`]: ./fn.write.html
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub unsafe fn read<T>(src: *const T) -> T {
576 let mut tmp = MaybeUninit::<T>::uninit();
577 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
581 /// Reads the value from `src` without moving it. This leaves the
582 /// memory in `src` unchanged.
584 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
588 /// Behavior is undefined if any of the following conditions are violated:
590 /// * `src` must be [valid] for reads.
592 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
593 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
594 /// value and the value at `*src` can [violate memory safety][read-ownership].
596 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
598 /// [`Copy`]: ../marker/trait.Copy.html
599 /// [`read`]: ./fn.read.html
600 /// [`write_unaligned`]: ./fn.write_unaligned.html
601 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
602 /// [valid]: ../ptr/index.html#safety
606 /// Access members of a packed struct by reference:
611 /// #[repr(packed, C)]
619 /// unaligned: 0x01020304,
623 /// // Take the address of a 32-bit integer which is not aligned.
624 /// // This must be done as a raw pointer; unaligned references are invalid.
625 /// let unaligned = &x.unaligned as *const u32;
627 /// // Dereferencing normally will emit an aligned load instruction,
628 /// // causing undefined behavior.
629 /// // let v = *unaligned; // ERROR
631 /// // Instead, use `read_unaligned` to read improperly aligned values.
632 /// let v = ptr::read_unaligned(unaligned);
637 /// // Accessing unaligned values directly is safe.
638 /// assert!(x.unaligned == v);
641 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
642 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
643 let mut tmp = MaybeUninit::<T>::uninit();
644 copy_nonoverlapping(src as *const u8,
645 tmp.as_mut_ptr() as *mut u8,
646 mem::size_of::<T>());
650 /// Overwrites a memory location with the given value without reading or
651 /// dropping the old value.
653 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
654 /// allocations or resources, so care should be taken not to overwrite an object
655 /// that should be dropped.
657 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
658 /// location pointed to by `dst`.
660 /// This is appropriate for initializing uninitialized memory, or overwriting
661 /// memory that has previously been [`read`] from.
663 /// [`read`]: ./fn.read.html
667 /// Behavior is undefined if any of the following conditions are violated:
669 /// * `dst` must be [valid] for writes.
671 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
674 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
676 /// [valid]: ../ptr/index.html#safety
677 /// [`write_unaligned`]: ./fn.write_unaligned.html
685 /// let y = &mut x as *mut i32;
689 /// std::ptr::write(y, z);
690 /// assert_eq!(std::ptr::read(y), 12);
694 /// Manually implement [`mem::swap`]:
699 /// fn swap<T>(a: &mut T, b: &mut T) {
701 /// // Create a bitwise copy of the value at `a` in `tmp`.
702 /// let tmp = ptr::read(a);
704 /// // Exiting at this point (either by explicitly returning or by
705 /// // calling a function which panics) would cause the value in `tmp` to
706 /// // be dropped while the same value is still referenced by `a`. This
707 /// // could trigger undefined behavior if `T` is not `Copy`.
709 /// // Create a bitwise copy of the value at `b` in `a`.
710 /// // This is safe because mutable references cannot alias.
711 /// ptr::copy_nonoverlapping(b, a, 1);
713 /// // As above, exiting here could trigger undefined behavior because
714 /// // the same value is referenced by `a` and `b`.
716 /// // Move `tmp` into `b`.
717 /// ptr::write(b, tmp);
719 /// // `tmp` has been moved (`write` takes ownership of its second argument),
720 /// // so nothing is dropped implicitly here.
724 /// let mut foo = "foo".to_owned();
725 /// let mut bar = "bar".to_owned();
727 /// swap(&mut foo, &mut bar);
729 /// assert_eq!(foo, "bar");
730 /// assert_eq!(bar, "foo");
733 /// [`mem::swap`]: ../mem/fn.swap.html
735 #[stable(feature = "rust1", since = "1.0.0")]
736 pub unsafe fn write<T>(dst: *mut T, src: T) {
737 intrinsics::move_val_init(&mut *dst, src)
740 /// Overwrites a memory location with the given value without reading or
741 /// dropping the old value.
743 /// Unlike [`write`], the pointer may be unaligned.
745 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
746 /// could leak allocations or resources, so care should be taken not to overwrite
747 /// an object that should be dropped.
749 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
750 /// location pointed to by `dst`.
752 /// This is appropriate for initializing uninitialized memory, or overwriting
753 /// memory that has previously been read with [`read_unaligned`].
755 /// [`write`]: ./fn.write.html
756 /// [`read_unaligned`]: ./fn.read_unaligned.html
760 /// Behavior is undefined if any of the following conditions are violated:
762 /// * `dst` must be [valid] for writes.
764 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
766 /// [valid]: ../ptr/index.html#safety
770 /// Access fields in a packed struct:
773 /// use std::{mem, ptr};
775 /// #[repr(packed, C)]
776 /// #[derive(Default)]
782 /// let v = 0x01020304;
783 /// let mut x: Packed = unsafe { mem::zeroed() };
786 /// // Take a reference to a 32-bit integer which is not aligned.
787 /// let unaligned = &mut x.unaligned as *mut u32;
789 /// // Dereferencing normally will emit an aligned store instruction,
790 /// // causing undefined behavior because the pointer is not aligned.
791 /// // *unaligned = v; // ERROR
793 /// // Instead, use `write_unaligned` to write improperly aligned values.
794 /// ptr::write_unaligned(unaligned, v);
797 /// // Accessing unaligned values directly is safe.
798 /// assert!(x.unaligned == v);
801 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
802 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
803 copy_nonoverlapping(&src as *const T as *const u8,
805 mem::size_of::<T>());
809 /// Performs a volatile read of the value from `src` without moving it. This
810 /// leaves the memory in `src` unchanged.
812 /// Volatile operations are intended to act on I/O memory, and are guaranteed
813 /// to not be elided or reordered by the compiler across other volatile
816 /// Memory accessed with `read_volatile` or [`write_volatile`] should not be
817 /// accessed with non-volatile operations.
819 /// [`write_volatile`]: ./fn.write_volatile.html
823 /// Rust does not currently have a rigorously and formally defined memory model,
824 /// so the precise semantics of what "volatile" means here is subject to change
825 /// over time. That being said, the semantics will almost always end up pretty
826 /// similar to [C11's definition of volatile][c11].
828 /// The compiler shouldn't change the relative order or number of volatile
829 /// memory operations. However, volatile memory operations on zero-sized types
830 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
831 /// and may be ignored.
833 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
837 /// Behavior is undefined if any of the following conditions are violated:
839 /// * `src` must be [valid] for reads.
841 /// * `src` must be properly aligned.
843 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
844 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
845 /// value and the value at `*src` can [violate memory safety][read-ownership].
846 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
849 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
851 /// [valid]: ../ptr/index.html#safety
852 /// [`Copy`]: ../marker/trait.Copy.html
853 /// [`read`]: ./fn.read.html
854 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
856 /// Just like in C, whether an operation is volatile has no bearing whatsoever
857 /// on questions involving concurrent access from multiple threads. Volatile
858 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
859 /// a race between a `read_volatile` and any write operation to the same location
860 /// is undefined behavior.
868 /// let y = &x as *const i32;
871 /// assert_eq!(std::ptr::read_volatile(y), 12);
875 #[stable(feature = "volatile", since = "1.9.0")]
876 pub unsafe fn read_volatile<T>(src: *const T) -> T {
877 intrinsics::volatile_load(src)
880 /// Performs a volatile write of a memory location with the given value without
881 /// reading or dropping the old value.
883 /// Volatile operations are intended to act on I/O memory, and are guaranteed
884 /// to not be elided or reordered by the compiler across other volatile
887 /// Memory accessed with [`read_volatile`] or `write_volatile` should not be
888 /// accessed with non-volatile operations.
890 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
891 /// could leak allocations or resources, so care should be taken not to overwrite
892 /// an object that should be dropped.
894 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
895 /// location pointed to by `dst`.
897 /// [`read_volatile`]: ./fn.read_volatile.html
901 /// Rust does not currently have a rigorously and formally defined memory model,
902 /// so the precise semantics of what "volatile" means here is subject to change
903 /// over time. That being said, the semantics will almost always end up pretty
904 /// similar to [C11's definition of volatile][c11].
906 /// The compiler shouldn't change the relative order or number of volatile
907 /// memory operations. However, volatile memory operations on zero-sized types
908 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
909 /// and may be ignored.
911 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
915 /// Behavior is undefined if any of the following conditions are violated:
917 /// * `dst` must be [valid] for writes.
919 /// * `dst` must be properly aligned.
921 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
923 /// [valid]: ../ptr/index.html#safety
925 /// Just like in C, whether an operation is volatile has no bearing whatsoever
926 /// on questions involving concurrent access from multiple threads. Volatile
927 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
928 /// a race between a `write_volatile` and any other operation (reading or writing)
929 /// on the same location is undefined behavior.
937 /// let y = &mut x as *mut i32;
941 /// std::ptr::write_volatile(y, z);
942 /// assert_eq!(std::ptr::read_volatile(y), 12);
946 #[stable(feature = "volatile", since = "1.9.0")]
947 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
948 intrinsics::volatile_store(dst, src);
951 #[lang = "const_ptr"]
952 impl<T: ?Sized> *const T {
953 /// Returns `true` if the pointer is null.
955 /// Note that unsized types have many possible null pointers, as only the
956 /// raw data pointer is considered, not their length, vtable, etc.
957 /// Therefore, two pointers that are null may still not compare equal to
965 /// let s: &str = "Follow the rabbit";
966 /// let ptr: *const u8 = s.as_ptr();
967 /// assert!(!ptr.is_null());
969 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn is_null(self) -> bool {
972 // Compare via a cast to a thin pointer, so fat pointers are only
973 // considering their "data" part for null-ness.
974 (self as *const u8) == null()
977 /// Returns `None` if the pointer is null, or else returns a reference to
978 /// the value wrapped in `Some`.
982 /// While this method and its mutable counterpart are useful for
983 /// null-safety, it is important to note that this is still an unsafe
984 /// operation because the returned value could be pointing to invalid
987 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
988 /// not necessarily reflect the actual lifetime of the data.
995 /// let ptr: *const u8 = &10u8 as *const u8;
998 /// if let Some(val_back) = ptr.as_ref() {
999 /// println!("We got back the value: {}!", val_back);
1004 /// # Null-unchecked version
1006 /// If you are sure the pointer can never be null and are looking for some kind of
1007 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1008 /// dereference the pointer directly.
1011 /// let ptr: *const u8 = &10u8 as *const u8;
1014 /// let val_back = &*ptr;
1015 /// println!("We got back the value: {}!", val_back);
1018 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1020 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1028 /// Calculates the offset from a pointer.
1030 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1031 /// offset of `3 * size_of::<T>()` bytes.
1035 /// If any of the following conditions are violated, the result is Undefined
1038 /// * Both the starting and resulting pointer must be either in bounds or one
1039 /// byte past the end of the same allocated object.
1041 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1043 /// * The offset being in bounds cannot rely on "wrapping around" the address
1044 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1046 /// The compiler and standard library generally tries to ensure allocations
1047 /// never reach a size where an offset is a concern. For instance, `Vec`
1048 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1049 /// `vec.as_ptr().add(vec.len())` is always safe.
1051 /// Most platforms fundamentally can't even construct such an allocation.
1052 /// For instance, no known 64-bit platform can ever serve a request
1053 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1054 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1055 /// more than `isize::MAX` bytes with things like Physical Address
1056 /// Extension. As such, memory acquired directly from allocators or memory
1057 /// mapped files *may* be too large to handle with this function.
1059 /// Consider using `wrapping_offset` instead if these constraints are
1060 /// difficult to satisfy. The only advantage of this method is that it
1061 /// enables more aggressive compiler optimizations.
1068 /// let s: &str = "123";
1069 /// let ptr: *const u8 = s.as_ptr();
1072 /// println!("{}", *ptr.offset(1) as char);
1073 /// println!("{}", *ptr.offset(2) as char);
1076 #[stable(feature = "rust1", since = "1.0.0")]
1078 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
1079 intrinsics::offset(self, count)
1082 /// Calculates the offset from a pointer using wrapping arithmetic.
1084 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1085 /// offset of `3 * size_of::<T>()` bytes.
1089 /// The resulting pointer does not need to be in bounds, but it is
1090 /// potentially hazardous to dereference (which requires `unsafe`).
1091 /// In particular, the resulting pointer may *not* be used to access a
1092 /// different allocated object than the one `self` points to. In other
1093 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1094 /// *not* the same as `y`, and dereferencing it is undefined behavior
1095 /// unless `x` and `y` point into the same allocated object.
1097 /// Always use `.offset(count)` instead when possible, because `offset`
1098 /// allows the compiler to optimize better. If you need to cross object
1099 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1106 /// // Iterate using a raw pointer in increments of two elements
1107 /// let data = [1u8, 2, 3, 4, 5];
1108 /// let mut ptr: *const u8 = data.as_ptr();
1110 /// let end_rounded_up = ptr.wrapping_offset(6);
1112 /// // This loop prints "1, 3, 5, "
1113 /// while ptr != end_rounded_up {
1115 /// print!("{}, ", *ptr);
1117 /// ptr = ptr.wrapping_offset(step);
1120 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1122 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
1124 intrinsics::arith_offset(self, count)
1128 /// Calculates the distance between two pointers. The returned value is in
1129 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1131 /// This function is the inverse of [`offset`].
1133 /// [`offset`]: #method.offset
1134 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
1138 /// If any of the following conditions are violated, the result is Undefined
1141 /// * Both the starting and other pointer must be either in bounds or one
1142 /// byte past the end of the same allocated object.
1144 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1146 /// * The distance between the pointers, in bytes, must be an exact multiple
1147 /// of the size of `T`.
1149 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1151 /// The compiler and standard library generally try to ensure allocations
1152 /// never reach a size where an offset is a concern. For instance, `Vec`
1153 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1154 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1156 /// Most platforms fundamentally can't even construct such an allocation.
1157 /// For instance, no known 64-bit platform can ever serve a request
1158 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1159 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1160 /// more than `isize::MAX` bytes with things like Physical Address
1161 /// Extension. As such, memory acquired directly from allocators or memory
1162 /// mapped files *may* be too large to handle with this function.
1164 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1165 /// difficult to satisfy. The only advantage of this method is that it
1166 /// enables more aggressive compiler optimizations.
1170 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1177 /// #![feature(ptr_offset_from)]
1180 /// let ptr1: *const i32 = &a[1];
1181 /// let ptr2: *const i32 = &a[3];
1183 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1184 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1185 /// assert_eq!(ptr1.offset(2), ptr2);
1186 /// assert_eq!(ptr2.offset(-2), ptr1);
1189 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1191 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1192 let pointee_size = mem::size_of::<T>();
1193 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1195 // This is the same sequence that Clang emits for pointer subtraction.
1196 // It can be neither `nsw` nor `nuw` because the input is treated as
1197 // unsigned but then the output is treated as signed, so neither works.
1198 let d = isize::wrapping_sub(self as _, origin as _);
1199 intrinsics::exact_div(d, pointee_size as _)
1202 /// Calculates the distance between two pointers. The returned value is in
1203 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1205 /// If the address different between the two pointers is not a multiple of
1206 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1209 /// Though this method is safe for any two pointers, note that its result
1210 /// will be mostly useless if the two pointers aren't into the same allocated
1211 /// object, for example if they point to two different local variables.
1215 /// This function panics if `T` is a zero-sized type.
1222 /// #![feature(ptr_wrapping_offset_from)]
1225 /// let ptr1: *const i32 = &a[1];
1226 /// let ptr2: *const i32 = &a[3];
1227 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1228 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1229 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1230 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1232 /// let ptr1: *const i32 = 3 as _;
1233 /// let ptr2: *const i32 = 13 as _;
1234 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1236 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1238 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1239 let pointee_size = mem::size_of::<T>();
1240 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1242 let d = isize::wrapping_sub(self as _, origin as _);
1243 d.wrapping_div(pointee_size as _)
1246 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1248 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1249 /// offset of `3 * size_of::<T>()` bytes.
1253 /// If any of the following conditions are violated, the result is Undefined
1256 /// * Both the starting and resulting pointer must be either in bounds or one
1257 /// byte past the end of the same allocated object.
1259 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1261 /// * The offset being in bounds cannot rely on "wrapping around" the address
1262 /// space. That is, the infinite-precision sum must fit in a `usize`.
1264 /// The compiler and standard library generally tries to ensure allocations
1265 /// never reach a size where an offset is a concern. For instance, `Vec`
1266 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1267 /// `vec.as_ptr().add(vec.len())` is always safe.
1269 /// Most platforms fundamentally can't even construct such an allocation.
1270 /// For instance, no known 64-bit platform can ever serve a request
1271 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1272 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1273 /// more than `isize::MAX` bytes with things like Physical Address
1274 /// Extension. As such, memory acquired directly from allocators or memory
1275 /// mapped files *may* be too large to handle with this function.
1277 /// Consider using `wrapping_offset` instead if these constraints are
1278 /// difficult to satisfy. The only advantage of this method is that it
1279 /// enables more aggressive compiler optimizations.
1286 /// let s: &str = "123";
1287 /// let ptr: *const u8 = s.as_ptr();
1290 /// println!("{}", *ptr.add(1) as char);
1291 /// println!("{}", *ptr.add(2) as char);
1294 #[stable(feature = "pointer_methods", since = "1.26.0")]
1296 pub unsafe fn add(self, count: usize) -> Self
1299 self.offset(count as isize)
1302 /// Calculates the offset from a pointer (convenience for
1303 /// `.offset((count as isize).wrapping_neg())`).
1305 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1306 /// offset of `3 * size_of::<T>()` bytes.
1310 /// If any of the following conditions are violated, the result is Undefined
1313 /// * Both the starting and resulting pointer must be either in bounds or one
1314 /// byte past the end of the same allocated object.
1316 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1318 /// * The offset being in bounds cannot rely on "wrapping around" the address
1319 /// space. That is, the infinite-precision sum must fit in a usize.
1321 /// The compiler and standard library generally tries to ensure allocations
1322 /// never reach a size where an offset is a concern. For instance, `Vec`
1323 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1324 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1326 /// Most platforms fundamentally can't even construct such an allocation.
1327 /// For instance, no known 64-bit platform can ever serve a request
1328 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1329 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1330 /// more than `isize::MAX` bytes with things like Physical Address
1331 /// Extension. As such, memory acquired directly from allocators or memory
1332 /// mapped files *may* be too large to handle with this function.
1334 /// Consider using `wrapping_offset` instead if these constraints are
1335 /// difficult to satisfy. The only advantage of this method is that it
1336 /// enables more aggressive compiler optimizations.
1343 /// let s: &str = "123";
1346 /// let end: *const u8 = s.as_ptr().add(3);
1347 /// println!("{}", *end.sub(1) as char);
1348 /// println!("{}", *end.sub(2) as char);
1351 #[stable(feature = "pointer_methods", since = "1.26.0")]
1353 pub unsafe fn sub(self, count: usize) -> Self
1356 self.offset((count as isize).wrapping_neg())
1359 /// Calculates the offset from a pointer using wrapping arithmetic.
1360 /// (convenience for `.wrapping_offset(count as isize)`)
1362 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1363 /// offset of `3 * size_of::<T>()` bytes.
1367 /// The resulting pointer does not need to be in bounds, but it is
1368 /// potentially hazardous to dereference (which requires `unsafe`).
1370 /// Always use `.add(count)` instead when possible, because `add`
1371 /// allows the compiler to optimize better.
1378 /// // Iterate using a raw pointer in increments of two elements
1379 /// let data = [1u8, 2, 3, 4, 5];
1380 /// let mut ptr: *const u8 = data.as_ptr();
1382 /// let end_rounded_up = ptr.wrapping_add(6);
1384 /// // This loop prints "1, 3, 5, "
1385 /// while ptr != end_rounded_up {
1387 /// print!("{}, ", *ptr);
1389 /// ptr = ptr.wrapping_add(step);
1392 #[stable(feature = "pointer_methods", since = "1.26.0")]
1394 pub fn wrapping_add(self, count: usize) -> Self
1397 self.wrapping_offset(count as isize)
1400 /// Calculates the offset from a pointer using wrapping arithmetic.
1401 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1403 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1404 /// offset of `3 * size_of::<T>()` bytes.
1408 /// The resulting pointer does not need to be in bounds, but it is
1409 /// potentially hazardous to dereference (which requires `unsafe`).
1411 /// Always use `.sub(count)` instead when possible, because `sub`
1412 /// allows the compiler to optimize better.
1419 /// // Iterate using a raw pointer in increments of two elements (backwards)
1420 /// let data = [1u8, 2, 3, 4, 5];
1421 /// let mut ptr: *const u8 = data.as_ptr();
1422 /// let start_rounded_down = ptr.wrapping_sub(2);
1423 /// ptr = ptr.wrapping_add(4);
1425 /// // This loop prints "5, 3, 1, "
1426 /// while ptr != start_rounded_down {
1428 /// print!("{}, ", *ptr);
1430 /// ptr = ptr.wrapping_sub(step);
1433 #[stable(feature = "pointer_methods", since = "1.26.0")]
1435 pub fn wrapping_sub(self, count: usize) -> Self
1438 self.wrapping_offset((count as isize).wrapping_neg())
1441 /// Reads the value from `self` without moving it. This leaves the
1442 /// memory in `self` unchanged.
1444 /// See [`ptr::read`] for safety concerns and examples.
1446 /// [`ptr::read`]: ./ptr/fn.read.html
1447 #[stable(feature = "pointer_methods", since = "1.26.0")]
1449 pub unsafe fn read(self) -> T
1455 /// Performs a volatile read of the value from `self` without moving it. This
1456 /// leaves the memory in `self` unchanged.
1458 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1459 /// to not be elided or reordered by the compiler across other volatile
1462 /// See [`ptr::read_volatile`] for safety concerns and examples.
1464 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
1465 #[stable(feature = "pointer_methods", since = "1.26.0")]
1467 pub unsafe fn read_volatile(self) -> T
1473 /// Reads the value from `self` without moving it. This leaves the
1474 /// memory in `self` unchanged.
1476 /// Unlike `read`, the pointer may be unaligned.
1478 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1480 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
1481 #[stable(feature = "pointer_methods", since = "1.26.0")]
1483 pub unsafe fn read_unaligned(self) -> T
1486 read_unaligned(self)
1489 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1490 /// and destination may overlap.
1492 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1494 /// See [`ptr::copy`] for safety concerns and examples.
1496 /// [`ptr::copy`]: ./ptr/fn.copy.html
1497 #[stable(feature = "pointer_methods", since = "1.26.0")]
1499 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1502 copy(self, dest, count)
1505 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1506 /// and destination may *not* overlap.
1508 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1510 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1512 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
1513 #[stable(feature = "pointer_methods", since = "1.26.0")]
1515 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1518 copy_nonoverlapping(self, dest, count)
1521 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1524 /// If it is not possible to align the pointer, the implementation returns
1525 /// `usize::max_value()`.
1527 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1528 /// used with the `offset` or `offset_to` methods.
1530 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
1531 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1532 /// the returned offset is correct in all terms other than alignment.
1536 /// The function panics if `align` is not a power-of-two.
1540 /// Accessing adjacent `u8` as `u16`
1543 /// # fn foo(n: usize) {
1544 /// # use std::mem::align_of;
1546 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1547 /// let ptr = &x[n] as *const u8;
1548 /// let offset = ptr.align_offset(align_of::<u16>());
1549 /// if offset < x.len() - n - 1 {
1550 /// let u16_ptr = ptr.add(offset) as *const u16;
1551 /// assert_ne!(*u16_ptr, 500);
1553 /// // while the pointer can be aligned via `offset`, it would point
1554 /// // outside the allocation
1558 #[stable(feature = "align_offset", since = "1.36.0")]
1559 pub fn align_offset(self, align: usize) -> usize where T: Sized {
1560 if !align.is_power_of_two() {
1561 panic!("align_offset: align is not a power-of-two");
1564 align_offset(self, align)
1571 impl<T: ?Sized> *mut T {
1572 /// Returns `true` if the pointer is null.
1574 /// Note that unsized types have many possible null pointers, as only the
1575 /// raw data pointer is considered, not their length, vtable, etc.
1576 /// Therefore, two pointers that are null may still not compare equal to
1584 /// let mut s = [1, 2, 3];
1585 /// let ptr: *mut u32 = s.as_mut_ptr();
1586 /// assert!(!ptr.is_null());
1588 #[stable(feature = "rust1", since = "1.0.0")]
1590 pub fn is_null(self) -> bool {
1591 // Compare via a cast to a thin pointer, so fat pointers are only
1592 // considering their "data" part for null-ness.
1593 (self as *mut u8) == null_mut()
1596 /// Returns `None` if the pointer is null, or else returns a reference to
1597 /// the value wrapped in `Some`.
1601 /// While this method and its mutable counterpart are useful for
1602 /// null-safety, it is important to note that this is still an unsafe
1603 /// operation because the returned value could be pointing to invalid
1606 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1607 /// not necessarily reflect the actual lifetime of the data.
1614 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1617 /// if let Some(val_back) = ptr.as_ref() {
1618 /// println!("We got back the value: {}!", val_back);
1623 /// # Null-unchecked version
1625 /// If you are sure the pointer can never be null and are looking for some kind of
1626 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
1627 /// dereference the pointer directly.
1630 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1633 /// let val_back = &*ptr;
1634 /// println!("We got back the value: {}!", val_back);
1637 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1639 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1647 /// Calculates the offset from a pointer.
1649 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1650 /// offset of `3 * size_of::<T>()` bytes.
1654 /// If any of the following conditions are violated, the result is Undefined
1657 /// * Both the starting and resulting pointer must be either in bounds or one
1658 /// byte past the end of the same allocated object.
1660 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1662 /// * The offset being in bounds cannot rely on "wrapping around" the address
1663 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1665 /// The compiler and standard library generally tries to ensure allocations
1666 /// never reach a size where an offset is a concern. For instance, `Vec`
1667 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1668 /// `vec.as_ptr().add(vec.len())` is always safe.
1670 /// Most platforms fundamentally can't even construct such an allocation.
1671 /// For instance, no known 64-bit platform can ever serve a request
1672 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1673 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1674 /// more than `isize::MAX` bytes with things like Physical Address
1675 /// Extension. As such, memory acquired directly from allocators or memory
1676 /// mapped files *may* be too large to handle with this function.
1678 /// Consider using `wrapping_offset` instead if these constraints are
1679 /// difficult to satisfy. The only advantage of this method is that it
1680 /// enables more aggressive compiler optimizations.
1687 /// let mut s = [1, 2, 3];
1688 /// let ptr: *mut u32 = s.as_mut_ptr();
1691 /// println!("{}", *ptr.offset(1));
1692 /// println!("{}", *ptr.offset(2));
1695 #[stable(feature = "rust1", since = "1.0.0")]
1697 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1698 intrinsics::offset(self, count) as *mut T
1701 /// Calculates the offset from a pointer using wrapping arithmetic.
1702 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1703 /// offset of `3 * size_of::<T>()` bytes.
1707 /// The resulting pointer does not need to be in bounds, but it is
1708 /// potentially hazardous to dereference (which requires `unsafe`).
1709 /// In particular, the resulting pointer may *not* be used to access a
1710 /// different allocated object than the one `self` points to. In other
1711 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1712 /// *not* the same as `y`, and dereferencing it is undefined behavior
1713 /// unless `x` and `y` point into the same allocated object.
1715 /// Always use `.offset(count)` instead when possible, because `offset`
1716 /// allows the compiler to optimize better. If you need to cross object
1717 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1724 /// // Iterate using a raw pointer in increments of two elements
1725 /// let mut data = [1u8, 2, 3, 4, 5];
1726 /// let mut ptr: *mut u8 = data.as_mut_ptr();
1728 /// let end_rounded_up = ptr.wrapping_offset(6);
1730 /// while ptr != end_rounded_up {
1734 /// ptr = ptr.wrapping_offset(step);
1736 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1738 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1740 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1742 intrinsics::arith_offset(self, count) as *mut T
1746 /// Returns `None` if the pointer is null, or else returns a mutable
1747 /// reference to the value wrapped in `Some`.
1751 /// As with `as_ref`, this is unsafe because it cannot verify the validity
1752 /// of the returned pointer, nor can it ensure that the lifetime `'a`
1753 /// returned is indeed a valid lifetime for the contained data.
1760 /// let mut s = [1, 2, 3];
1761 /// let ptr: *mut u32 = s.as_mut_ptr();
1762 /// let first_value = unsafe { ptr.as_mut().unwrap() };
1763 /// *first_value = 4;
1764 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1766 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1768 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1776 /// Calculates the distance between two pointers. The returned value is in
1777 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1779 /// This function is the inverse of [`offset`].
1781 /// [`offset`]: #method.offset-1
1782 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
1786 /// If any of the following conditions are violated, the result is Undefined
1789 /// * Both the starting and other pointer must be either in bounds or one
1790 /// byte past the end of the same allocated object.
1792 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1794 /// * The distance between the pointers, in bytes, must be an exact multiple
1795 /// of the size of `T`.
1797 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1799 /// The compiler and standard library generally try to ensure allocations
1800 /// never reach a size where an offset is a concern. For instance, `Vec`
1801 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1802 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1804 /// Most platforms fundamentally can't even construct such an allocation.
1805 /// For instance, no known 64-bit platform can ever serve a request
1806 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1807 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1808 /// more than `isize::MAX` bytes with things like Physical Address
1809 /// Extension. As such, memory acquired directly from allocators or memory
1810 /// mapped files *may* be too large to handle with this function.
1812 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1813 /// difficult to satisfy. The only advantage of this method is that it
1814 /// enables more aggressive compiler optimizations.
1818 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1825 /// #![feature(ptr_offset_from)]
1827 /// let mut a = [0; 5];
1828 /// let ptr1: *mut i32 = &mut a[1];
1829 /// let ptr2: *mut i32 = &mut a[3];
1831 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1832 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1833 /// assert_eq!(ptr1.offset(2), ptr2);
1834 /// assert_eq!(ptr2.offset(-2), ptr1);
1837 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1839 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1840 (self as *const T).offset_from(origin)
1843 /// Calculates the distance between two pointers. The returned value is in
1844 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1846 /// If the address different between the two pointers is not a multiple of
1847 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1850 /// Though this method is safe for any two pointers, note that its result
1851 /// will be mostly useless if the two pointers aren't into the same allocated
1852 /// object, for example if they point to two different local variables.
1856 /// This function panics if `T` is a zero-sized type.
1863 /// #![feature(ptr_wrapping_offset_from)]
1865 /// let mut a = [0; 5];
1866 /// let ptr1: *mut i32 = &mut a[1];
1867 /// let ptr2: *mut i32 = &mut a[3];
1868 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1869 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1870 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1871 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1873 /// let ptr1: *mut i32 = 3 as _;
1874 /// let ptr2: *mut i32 = 13 as _;
1875 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1877 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1879 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1880 (self as *const T).wrapping_offset_from(origin)
1883 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1885 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1886 /// offset of `3 * size_of::<T>()` bytes.
1890 /// If any of the following conditions are violated, the result is Undefined
1893 /// * Both the starting and resulting pointer must be either in bounds or one
1894 /// byte past the end of the same allocated object.
1896 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1898 /// * The offset being in bounds cannot rely on "wrapping around" the address
1899 /// space. That is, the infinite-precision sum must fit in a `usize`.
1901 /// The compiler and standard library generally tries to ensure allocations
1902 /// never reach a size where an offset is a concern. For instance, `Vec`
1903 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1904 /// `vec.as_ptr().add(vec.len())` is always safe.
1906 /// Most platforms fundamentally can't even construct such an allocation.
1907 /// For instance, no known 64-bit platform can ever serve a request
1908 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1909 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1910 /// more than `isize::MAX` bytes with things like Physical Address
1911 /// Extension. As such, memory acquired directly from allocators or memory
1912 /// mapped files *may* be too large to handle with this function.
1914 /// Consider using `wrapping_offset` instead if these constraints are
1915 /// difficult to satisfy. The only advantage of this method is that it
1916 /// enables more aggressive compiler optimizations.
1923 /// let s: &str = "123";
1924 /// let ptr: *const u8 = s.as_ptr();
1927 /// println!("{}", *ptr.add(1) as char);
1928 /// println!("{}", *ptr.add(2) as char);
1931 #[stable(feature = "pointer_methods", since = "1.26.0")]
1933 pub unsafe fn add(self, count: usize) -> Self
1936 self.offset(count as isize)
1939 /// Calculates the offset from a pointer (convenience for
1940 /// `.offset((count as isize).wrapping_neg())`).
1942 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1943 /// offset of `3 * size_of::<T>()` bytes.
1947 /// If any of the following conditions are violated, the result is Undefined
1950 /// * Both the starting and resulting pointer must be either in bounds or one
1951 /// byte past the end of the same allocated object.
1953 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1955 /// * The offset being in bounds cannot rely on "wrapping around" the address
1956 /// space. That is, the infinite-precision sum must fit in a usize.
1958 /// The compiler and standard library generally tries to ensure allocations
1959 /// never reach a size where an offset is a concern. For instance, `Vec`
1960 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1961 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1963 /// Most platforms fundamentally can't even construct such an allocation.
1964 /// For instance, no known 64-bit platform can ever serve a request
1965 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1966 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1967 /// more than `isize::MAX` bytes with things like Physical Address
1968 /// Extension. As such, memory acquired directly from allocators or memory
1969 /// mapped files *may* be too large to handle with this function.
1971 /// Consider using `wrapping_offset` instead if these constraints are
1972 /// difficult to satisfy. The only advantage of this method is that it
1973 /// enables more aggressive compiler optimizations.
1980 /// let s: &str = "123";
1983 /// let end: *const u8 = s.as_ptr().add(3);
1984 /// println!("{}", *end.sub(1) as char);
1985 /// println!("{}", *end.sub(2) as char);
1988 #[stable(feature = "pointer_methods", since = "1.26.0")]
1990 pub unsafe fn sub(self, count: usize) -> Self
1993 self.offset((count as isize).wrapping_neg())
1996 /// Calculates the offset from a pointer using wrapping arithmetic.
1997 /// (convenience for `.wrapping_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 /// The resulting pointer does not need to be in bounds, but it is
2005 /// potentially hazardous to dereference (which requires `unsafe`).
2007 /// Always use `.add(count)` instead when possible, because `add`
2008 /// allows the compiler to optimize better.
2015 /// // Iterate using a raw pointer in increments of two elements
2016 /// let data = [1u8, 2, 3, 4, 5];
2017 /// let mut ptr: *const u8 = data.as_ptr();
2019 /// let end_rounded_up = ptr.wrapping_add(6);
2021 /// // This loop prints "1, 3, 5, "
2022 /// while ptr != end_rounded_up {
2024 /// print!("{}, ", *ptr);
2026 /// ptr = ptr.wrapping_add(step);
2029 #[stable(feature = "pointer_methods", since = "1.26.0")]
2031 pub fn wrapping_add(self, count: usize) -> Self
2034 self.wrapping_offset(count as isize)
2037 /// Calculates the offset from a pointer using wrapping arithmetic.
2038 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
2040 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
2041 /// offset of `3 * size_of::<T>()` bytes.
2045 /// The resulting pointer does not need to be in bounds, but it is
2046 /// potentially hazardous to dereference (which requires `unsafe`).
2048 /// Always use `.sub(count)` instead when possible, because `sub`
2049 /// allows the compiler to optimize better.
2056 /// // Iterate using a raw pointer in increments of two elements (backwards)
2057 /// let data = [1u8, 2, 3, 4, 5];
2058 /// let mut ptr: *const u8 = data.as_ptr();
2059 /// let start_rounded_down = ptr.wrapping_sub(2);
2060 /// ptr = ptr.wrapping_add(4);
2062 /// // This loop prints "5, 3, 1, "
2063 /// while ptr != start_rounded_down {
2065 /// print!("{}, ", *ptr);
2067 /// ptr = ptr.wrapping_sub(step);
2070 #[stable(feature = "pointer_methods", since = "1.26.0")]
2072 pub fn wrapping_sub(self, count: usize) -> Self
2075 self.wrapping_offset((count as isize).wrapping_neg())
2078 /// Reads the value from `self` without moving it. This leaves the
2079 /// memory in `self` unchanged.
2081 /// See [`ptr::read`] for safety concerns and examples.
2083 /// [`ptr::read`]: ./ptr/fn.read.html
2084 #[stable(feature = "pointer_methods", since = "1.26.0")]
2086 pub unsafe fn read(self) -> T
2092 /// Performs a volatile read of the value from `self` without moving it. This
2093 /// leaves the memory in `self` unchanged.
2095 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2096 /// to not be elided or reordered by the compiler across other volatile
2099 /// See [`ptr::read_volatile`] for safety concerns and examples.
2101 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
2102 #[stable(feature = "pointer_methods", since = "1.26.0")]
2104 pub unsafe fn read_volatile(self) -> T
2110 /// Reads the value from `self` without moving it. This leaves the
2111 /// memory in `self` unchanged.
2113 /// Unlike `read`, the pointer may be unaligned.
2115 /// See [`ptr::read_unaligned`] for safety concerns and examples.
2117 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
2118 #[stable(feature = "pointer_methods", since = "1.26.0")]
2120 pub unsafe fn read_unaligned(self) -> T
2123 read_unaligned(self)
2126 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2127 /// and destination may overlap.
2129 /// NOTE: this has the *same* argument order as [`ptr::copy`].
2131 /// See [`ptr::copy`] for safety concerns and examples.
2133 /// [`ptr::copy`]: ./ptr/fn.copy.html
2134 #[stable(feature = "pointer_methods", since = "1.26.0")]
2136 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
2139 copy(self, dest, count)
2142 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2143 /// and destination may *not* overlap.
2145 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
2147 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2149 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2150 #[stable(feature = "pointer_methods", since = "1.26.0")]
2152 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
2155 copy_nonoverlapping(self, dest, count)
2158 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2159 /// and destination may overlap.
2161 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
2163 /// See [`ptr::copy`] for safety concerns and examples.
2165 /// [`ptr::copy`]: ./ptr/fn.copy.html
2166 #[stable(feature = "pointer_methods", since = "1.26.0")]
2168 pub unsafe fn copy_from(self, src: *const T, count: usize)
2171 copy(src, self, count)
2174 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2175 /// and destination may *not* overlap.
2177 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
2179 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
2181 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
2182 #[stable(feature = "pointer_methods", since = "1.26.0")]
2184 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
2187 copy_nonoverlapping(src, self, count)
2190 /// Executes the destructor (if any) of the pointed-to value.
2192 /// See [`ptr::drop_in_place`] for safety concerns and examples.
2194 /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
2195 #[stable(feature = "pointer_methods", since = "1.26.0")]
2197 pub unsafe fn drop_in_place(self) {
2201 /// Overwrites a memory location with the given value without reading or
2202 /// dropping the old value.
2204 /// See [`ptr::write`] for safety concerns and examples.
2206 /// [`ptr::write`]: ./ptr/fn.write.html
2207 #[stable(feature = "pointer_methods", since = "1.26.0")]
2209 pub unsafe fn write(self, val: T)
2215 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
2216 /// bytes of memory starting at `self` to `val`.
2218 /// See [`ptr::write_bytes`] for safety concerns and examples.
2220 /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
2221 #[stable(feature = "pointer_methods", since = "1.26.0")]
2223 pub unsafe fn write_bytes(self, val: u8, count: usize)
2226 write_bytes(self, val, count)
2229 /// Performs a volatile write of a memory location with the given value without
2230 /// reading or dropping the old value.
2232 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2233 /// to not be elided or reordered by the compiler across other volatile
2236 /// See [`ptr::write_volatile`] for safety concerns and examples.
2238 /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
2239 #[stable(feature = "pointer_methods", since = "1.26.0")]
2241 pub unsafe fn write_volatile(self, val: T)
2244 write_volatile(self, val)
2247 /// Overwrites a memory location with the given value without reading or
2248 /// dropping the old value.
2250 /// Unlike `write`, the pointer may be unaligned.
2252 /// See [`ptr::write_unaligned`] for safety concerns and examples.
2254 /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
2255 #[stable(feature = "pointer_methods", since = "1.26.0")]
2257 pub unsafe fn write_unaligned(self, val: T)
2260 write_unaligned(self, val)
2263 /// Replaces the value at `self` with `src`, returning the old
2264 /// value, without dropping either.
2266 /// See [`ptr::replace`] for safety concerns and examples.
2268 /// [`ptr::replace`]: ./ptr/fn.replace.html
2269 #[stable(feature = "pointer_methods", since = "1.26.0")]
2271 pub unsafe fn replace(self, src: T) -> T
2277 /// Swaps the values at two mutable locations of the same type, without
2278 /// deinitializing either. They may overlap, unlike `mem::swap` which is
2279 /// otherwise equivalent.
2281 /// See [`ptr::swap`] for safety concerns and examples.
2283 /// [`ptr::swap`]: ./ptr/fn.swap.html
2284 #[stable(feature = "pointer_methods", since = "1.26.0")]
2286 pub unsafe fn swap(self, with: *mut T)
2292 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
2295 /// If it is not possible to align the pointer, the implementation returns
2296 /// `usize::max_value()`.
2298 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
2299 /// used with the `offset` or `offset_to` methods.
2301 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
2302 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
2303 /// the returned offset is correct in all terms other than alignment.
2307 /// The function panics if `align` is not a power-of-two.
2311 /// Accessing adjacent `u8` as `u16`
2314 /// # fn foo(n: usize) {
2315 /// # use std::mem::align_of;
2317 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
2318 /// let ptr = &x[n] as *const u8;
2319 /// let offset = ptr.align_offset(align_of::<u16>());
2320 /// if offset < x.len() - n - 1 {
2321 /// let u16_ptr = ptr.add(offset) as *const u16;
2322 /// assert_ne!(*u16_ptr, 500);
2324 /// // while the pointer can be aligned via `offset`, it would point
2325 /// // outside the allocation
2329 #[stable(feature = "align_offset", since = "1.36.0")]
2330 pub fn align_offset(self, align: usize) -> usize where T: Sized {
2331 if !align.is_power_of_two() {
2332 panic!("align_offset: align is not a power-of-two");
2335 align_offset(self, align)
2340 /// Align pointer `p`.
2342 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
2343 /// to pointer `p` so that pointer `p` would get aligned to `a`.
2345 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
2346 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2349 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2350 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2351 /// than trying to adapt this to accommodate that change.
2353 /// Any questions go to @nagisa.
2354 #[lang="align_offset"]
2355 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2356 /// Calculate multiplicative modular inverse of `x` modulo `m`.
2358 /// This implementation is tailored for align_offset and has following preconditions:
2360 /// * `m` is a power-of-two;
2361 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2363 /// Implementation of this function shall not panic. Ever.
2365 fn mod_inv(x: usize, m: usize) -> usize {
2366 /// Multiplicative modular inverse table modulo 2⁴ = 16.
2368 /// Note, that this table does not contain values where inverse does not exist (i.e., for
2369 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2370 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2371 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2372 const INV_TABLE_MOD: usize = 16;
2374 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
2376 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
2377 if m <= INV_TABLE_MOD {
2378 table_inverse & (m - 1)
2380 // We iterate "up" using the following formula:
2382 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2384 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
2385 let mut inverse = table_inverse;
2386 let mut going_mod = INV_TABLE_MOD_SQUARED;
2388 // y = y * (2 - xy) mod n
2390 // Note, that we use wrapping operations here intentionally – the original formula
2391 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
2392 // usize::max_value()` instead, because we take the result `mod n` at the end
2394 inverse = inverse.wrapping_mul(
2395 2usize.wrapping_sub(x.wrapping_mul(inverse))
2396 ) & (going_mod - 1);
2398 return inverse & (m - 1);
2400 going_mod = going_mod.wrapping_mul(going_mod);
2405 let stride = mem::size_of::<T>();
2406 let a_minus_one = a.wrapping_sub(1);
2407 let pmoda = p as usize & a_minus_one;
2410 // Already aligned. Yay!
2415 return if stride == 0 {
2416 // If the pointer is not aligned, and the element is zero-sized, then no amount of
2417 // elements will ever align the pointer.
2420 a.wrapping_sub(pmoda)
2424 let smoda = stride & a_minus_one;
2425 // a is power-of-two so cannot be 0. stride = 0 is handled above.
2426 let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
2427 let gcd = 1usize << gcdpow;
2429 if p as usize & (gcd - 1) == 0 {
2430 // This branch solves for the following linear congruence equation:
2432 // $$ p + so ≡ 0 mod a $$
2434 // $p$ here is the pointer value, $s$ – stride of `T`, $o$ offset in `T`s, and $a$ – the
2435 // requested alignment.
2438 // o = (a - (p mod a))/g * ((s/g)⁻¹ mod a)
2440 // The first term is “the relative alignment of p to a”, the second term is “how does
2441 // incrementing p by s bytes change the relative alignment of p”. Division by `g` is
2442 // necessary to make this equation well formed if $a$ and $s$ are not co-prime.
2444 // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
2445 // to take the result $o mod lcm(s, a)$. We can replace $lcm(s, a)$ with just a $a / g$.
2446 let j = a.wrapping_sub(pmoda) >> gcdpow;
2447 let k = smoda >> gcdpow;
2448 return intrinsics::unchecked_rem(j.wrapping_mul(mod_inv(k, a)), a >> gcdpow);
2451 // Cannot be aligned at all.
2457 // Equality for pointers
2458 #[stable(feature = "rust1", since = "1.0.0")]
2459 impl<T: ?Sized> PartialEq for *const T {
2461 fn eq(&self, other: &*const T) -> bool { *self == *other }
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 impl<T: ?Sized> Eq for *const T {}
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 impl<T: ?Sized> PartialEq for *mut T {
2470 fn eq(&self, other: &*mut T) -> bool { *self == *other }
2473 #[stable(feature = "rust1", since = "1.0.0")]
2474 impl<T: ?Sized> Eq for *mut T {}
2476 /// Compares raw pointers for equality.
2478 /// This is the same as using the `==` operator, but less generic:
2479 /// the arguments have to be `*const T` raw pointers,
2480 /// not anything that implements `PartialEq`.
2482 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2483 /// by their address rather than comparing the values they point to
2484 /// (which is what the `PartialEq for &T` implementation does).
2492 /// let other_five = 5;
2493 /// let five_ref = &five;
2494 /// let same_five_ref = &five;
2495 /// let other_five_ref = &other_five;
2497 /// assert!(five_ref == same_five_ref);
2498 /// assert!(ptr::eq(five_ref, same_five_ref));
2500 /// assert!(five_ref == other_five_ref);
2501 /// assert!(!ptr::eq(five_ref, other_five_ref));
2504 /// Slices are also compared by their length (fat pointers):
2507 /// let a = [1, 2, 3];
2508 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
2509 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
2510 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
2513 /// Traits are also compared by their implementation:
2516 /// #[repr(transparent)]
2517 /// struct Wrapper { member: i32 }
2520 /// impl Trait for Wrapper {}
2521 /// impl Trait for i32 {}
2524 /// let wrapper = Wrapper { member: 10 };
2526 /// // Pointers have equal addresses.
2527 /// assert!(std::ptr::eq(
2528 /// &wrapper as *const Wrapper as *const u8,
2529 /// &wrapper.member as *const i32 as *const u8
2532 /// // Objects have equal addresses, but `Trait` has different implementations.
2533 /// assert!(!std::ptr::eq(
2534 /// &wrapper as &dyn Trait,
2535 /// &wrapper.member as &dyn Trait,
2537 /// assert!(!std::ptr::eq(
2538 /// &wrapper as &dyn Trait as *const dyn Trait,
2539 /// &wrapper.member as &dyn Trait as *const dyn Trait,
2542 /// // Converting the reference to a `*const u8` compares by address.
2543 /// assert!(std::ptr::eq(
2544 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
2545 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
2549 #[stable(feature = "ptr_eq", since = "1.17.0")]
2551 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2555 /// Hash a raw pointer.
2557 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
2558 /// by its address rather than the value it points to
2559 /// (which is what the `Hash for &T` implementation does).
2564 /// use std::collections::hash_map::DefaultHasher;
2565 /// use std::hash::{Hash, Hasher};
2569 /// let five_ref = &five;
2571 /// let mut hasher = DefaultHasher::new();
2572 /// ptr::hash(five_ref, &mut hasher);
2573 /// let actual = hasher.finish();
2575 /// let mut hasher = DefaultHasher::new();
2576 /// (five_ref as *const i32).hash(&mut hasher);
2577 /// let expected = hasher.finish();
2579 /// assert_eq!(actual, expected);
2581 #[stable(feature = "ptr_hash", since = "1.35.0")]
2582 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
2583 use crate::hash::Hash;
2587 // Impls for function pointers
2588 macro_rules! fnptr_impls_safety_abi {
2589 ($FnTy: ty, $($Arg: ident),*) => {
2590 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2591 impl<Ret, $($Arg),*> PartialEq for $FnTy {
2593 fn eq(&self, other: &Self) -> bool {
2594 *self as usize == *other as usize
2598 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2599 impl<Ret, $($Arg),*> Eq for $FnTy {}
2601 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2602 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2604 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2605 (*self as usize).partial_cmp(&(*other as usize))
2609 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2610 impl<Ret, $($Arg),*> Ord for $FnTy {
2612 fn cmp(&self, other: &Self) -> Ordering {
2613 (*self as usize).cmp(&(*other as usize))
2617 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2618 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2619 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2620 state.write_usize(*self as usize)
2624 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2625 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2627 fmt::Pointer::fmt(&(*self as *const ()), f)
2631 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2632 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2634 fmt::Pointer::fmt(&(*self as *const ()), f)
2640 macro_rules! fnptr_impls_args {
2641 ($($Arg: ident),+) => {
2642 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2643 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2644 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2645 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2646 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2647 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2650 // No variadic functions with 0 parameters
2651 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2652 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2653 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2654 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2658 fnptr_impls_args! { }
2659 fnptr_impls_args! { A }
2660 fnptr_impls_args! { A, B }
2661 fnptr_impls_args! { A, B, C }
2662 fnptr_impls_args! { A, B, C, D }
2663 fnptr_impls_args! { A, B, C, D, E }
2664 fnptr_impls_args! { A, B, C, D, E, F }
2665 fnptr_impls_args! { A, B, C, D, E, F, G }
2666 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2667 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2668 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2669 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2670 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2672 // Comparison for pointers
2673 #[stable(feature = "rust1", since = "1.0.0")]
2674 impl<T: ?Sized> Ord for *const T {
2676 fn cmp(&self, other: &*const T) -> Ordering {
2679 } else if self == other {
2687 #[stable(feature = "rust1", since = "1.0.0")]
2688 impl<T: ?Sized> PartialOrd for *const T {
2690 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2691 Some(self.cmp(other))
2695 fn lt(&self, other: &*const T) -> bool { *self < *other }
2698 fn le(&self, other: &*const T) -> bool { *self <= *other }
2701 fn gt(&self, other: &*const T) -> bool { *self > *other }
2704 fn ge(&self, other: &*const T) -> bool { *self >= *other }
2707 #[stable(feature = "rust1", since = "1.0.0")]
2708 impl<T: ?Sized> Ord for *mut T {
2710 fn cmp(&self, other: &*mut T) -> Ordering {
2713 } else if self == other {
2721 #[stable(feature = "rust1", since = "1.0.0")]
2722 impl<T: ?Sized> PartialOrd for *mut T {
2724 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2725 Some(self.cmp(other))
2729 fn lt(&self, other: &*mut T) -> bool { *self < *other }
2732 fn le(&self, other: &*mut T) -> bool { *self <= *other }
2735 fn gt(&self, other: &*mut T) -> bool { *self > *other }
2738 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
2741 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
2742 /// of this wrapper owns the referent. Useful for building abstractions like
2743 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
2745 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
2746 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
2747 /// the kind of strong aliasing guarantees an instance of `T` can expect:
2748 /// the referent of the pointer should not be modified without a unique path to
2749 /// its owning Unique.
2751 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
2752 /// consider using `NonNull`, which has weaker semantics.
2754 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2755 /// is never dereferenced. This is so that enums may use this forbidden value
2756 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
2757 /// However the pointer may still dangle if it isn't dereferenced.
2759 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
2760 /// for any type which upholds Unique's aliasing requirements.
2761 #[unstable(feature = "ptr_internals", issue = "0",
2762 reason = "use NonNull instead and consider PhantomData<T> \
2763 (if you also use #[may_dangle]), Send, and/or Sync")]
2765 #[repr(transparent)]
2766 #[rustc_layout_scalar_valid_range_start(1)]
2767 pub struct Unique<T: ?Sized> {
2769 // NOTE: this marker has no consequences for variance, but is necessary
2770 // for dropck to understand that we logically own a `T`.
2772 // For details, see:
2773 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
2774 _marker: PhantomData<T>,
2777 #[unstable(feature = "ptr_internals", issue = "0")]
2778 impl<T: ?Sized> fmt::Debug for Unique<T> {
2779 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2780 fmt::Pointer::fmt(&self.as_ptr(), f)
2784 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
2785 /// reference is unaliased. Note that this aliasing invariant is
2786 /// unenforced by the type system; the abstraction using the
2787 /// `Unique` must enforce it.
2788 #[unstable(feature = "ptr_internals", issue = "0")]
2789 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
2791 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
2792 /// reference is unaliased. Note that this aliasing invariant is
2793 /// unenforced by the type system; the abstraction using the
2794 /// `Unique` must enforce it.
2795 #[unstable(feature = "ptr_internals", issue = "0")]
2796 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
2798 #[unstable(feature = "ptr_internals", issue = "0")]
2799 impl<T: Sized> Unique<T> {
2800 /// Creates a new `Unique` that is dangling, but well-aligned.
2802 /// This is useful for initializing types which lazily allocate, like
2803 /// `Vec::new` does.
2805 /// Note that the pointer value may potentially represent a valid pointer to
2806 /// a `T`, which means this must not be used as a "not yet initialized"
2807 /// sentinel value. Types that lazily allocate must track initialization by
2808 /// some other means.
2809 // FIXME: rename to dangling() to match NonNull?
2810 pub const fn empty() -> Self {
2812 Unique::new_unchecked(mem::align_of::<T>() as *mut T)
2817 #[unstable(feature = "ptr_internals", issue = "0")]
2818 impl<T: ?Sized> Unique<T> {
2819 /// Creates a new `Unique`.
2823 /// `ptr` must be non-null.
2824 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2825 Unique { pointer: ptr as _, _marker: PhantomData }
2828 /// Creates a new `Unique` if `ptr` is non-null.
2829 pub fn new(ptr: *mut T) -> Option<Self> {
2831 Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
2837 /// Acquires the underlying `*mut` pointer.
2838 pub const fn as_ptr(self) -> *mut T {
2839 self.pointer as *mut T
2842 /// Dereferences the content.
2844 /// The resulting lifetime is bound to self so this behaves "as if"
2845 /// it were actually an instance of T that is getting borrowed. If a longer
2846 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2847 pub unsafe fn as_ref(&self) -> &T {
2851 /// Mutably dereferences the content.
2853 /// The resulting lifetime is bound to self so this behaves "as if"
2854 /// it were actually an instance of T that is getting borrowed. If a longer
2855 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2856 pub unsafe fn as_mut(&mut self) -> &mut T {
2861 #[unstable(feature = "ptr_internals", issue = "0")]
2862 impl<T: ?Sized> Clone for Unique<T> {
2863 fn clone(&self) -> Self {
2868 #[unstable(feature = "ptr_internals", issue = "0")]
2869 impl<T: ?Sized> Copy for Unique<T> { }
2871 #[unstable(feature = "ptr_internals", issue = "0")]
2872 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
2874 #[unstable(feature = "ptr_internals", issue = "0")]
2875 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> { }
2877 #[unstable(feature = "ptr_internals", issue = "0")]
2878 impl<T: ?Sized> fmt::Pointer for Unique<T> {
2879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2880 fmt::Pointer::fmt(&self.as_ptr(), f)
2884 #[unstable(feature = "ptr_internals", issue = "0")]
2885 impl<T: ?Sized> From<&mut T> for Unique<T> {
2886 fn from(reference: &mut T) -> Self {
2887 unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
2891 #[unstable(feature = "ptr_internals", issue = "0")]
2892 impl<T: ?Sized> From<&T> for Unique<T> {
2893 fn from(reference: &T) -> Self {
2894 unsafe { Unique { pointer: reference as *const T, _marker: PhantomData } }
2898 #[unstable(feature = "ptr_internals", issue = "0")]
2899 impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
2900 fn from(p: NonNull<T>) -> Self {
2901 unsafe { Unique { pointer: p.pointer, _marker: PhantomData } }
2905 /// `*mut T` but non-zero and covariant.
2907 /// This is often the correct thing to use when building data structures using
2908 /// raw pointers, but is ultimately more dangerous to use because of its additional
2909 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
2911 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2912 /// is never dereferenced. This is so that enums may use this forbidden value
2913 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
2914 /// However the pointer may still dangle if it isn't dereferenced.
2916 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
2917 /// for your use case, you should include some [`PhantomData`] in your type to
2918 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
2919 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
2920 /// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they
2921 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
2923 /// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
2924 /// not change the fact that mutating through a (pointer derived from a) shared
2925 /// reference is undefined behavior unless the mutation happens inside an
2926 /// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
2927 /// reference. When using this `From` instance without an `UnsafeCell<T>`,
2928 /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
2929 /// is never used for mutation.
2931 /// [`PhantomData`]: ../marker/struct.PhantomData.html
2932 /// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
2933 #[stable(feature = "nonnull", since = "1.25.0")]
2934 #[repr(transparent)]
2935 #[rustc_layout_scalar_valid_range_start(1)]
2936 pub struct NonNull<T: ?Sized> {
2940 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
2941 // N.B., this impl is unnecessary, but should provide better error messages.
2942 #[stable(feature = "nonnull", since = "1.25.0")]
2943 impl<T: ?Sized> !Send for NonNull<T> { }
2945 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
2946 // N.B., this impl is unnecessary, but should provide better error messages.
2947 #[stable(feature = "nonnull", since = "1.25.0")]
2948 impl<T: ?Sized> !Sync for NonNull<T> { }
2950 impl<T: Sized> NonNull<T> {
2951 /// Creates a new `NonNull` that is dangling, but well-aligned.
2953 /// This is useful for initializing types which lazily allocate, like
2954 /// `Vec::new` does.
2956 /// Note that the pointer value may potentially represent a valid pointer to
2957 /// a `T`, which means this must not be used as a "not yet initialized"
2958 /// sentinel value. Types that lazily allocate must track initialization by
2959 /// some other means.
2960 #[stable(feature = "nonnull", since = "1.25.0")]
2962 #[rustc_const_unstable(feature = "const_ptr_nonnull")]
2963 pub const fn dangling() -> Self {
2965 let ptr = mem::align_of::<T>() as *mut T;
2966 NonNull::new_unchecked(ptr)
2971 impl<T: ?Sized> NonNull<T> {
2972 /// Creates a new `NonNull`.
2976 /// `ptr` must be non-null.
2977 #[stable(feature = "nonnull", since = "1.25.0")]
2979 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2980 NonNull { pointer: ptr as _ }
2983 /// Creates a new `NonNull` if `ptr` is non-null.
2984 #[stable(feature = "nonnull", since = "1.25.0")]
2986 pub fn new(ptr: *mut T) -> Option<Self> {
2988 Some(unsafe { Self::new_unchecked(ptr) })
2994 /// Acquires the underlying `*mut` pointer.
2995 #[stable(feature = "nonnull", since = "1.25.0")]
2997 pub const fn as_ptr(self) -> *mut T {
2998 self.pointer as *mut T
3001 /// Dereferences the content.
3003 /// The resulting lifetime is bound to self so this behaves "as if"
3004 /// it were actually an instance of T that is getting borrowed. If a longer
3005 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
3006 #[stable(feature = "nonnull", since = "1.25.0")]
3008 pub unsafe fn as_ref(&self) -> &T {
3012 /// Mutably dereferences the content.
3014 /// The resulting lifetime is bound to self so this behaves "as if"
3015 /// it were actually an instance of T that is getting borrowed. If a longer
3016 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
3017 #[stable(feature = "nonnull", since = "1.25.0")]
3019 pub unsafe fn as_mut(&mut self) -> &mut T {
3023 /// Cast to a pointer of another type
3024 #[stable(feature = "nonnull_cast", since = "1.27.0")]
3026 #[rustc_const_unstable(feature = "const_ptr_nonnull")]
3027 pub const fn cast<U>(self) -> NonNull<U> {
3029 NonNull::new_unchecked(self.as_ptr() as *mut U)
3034 #[stable(feature = "nonnull", since = "1.25.0")]
3035 impl<T: ?Sized> Clone for NonNull<T> {
3036 fn clone(&self) -> Self {
3041 #[stable(feature = "nonnull", since = "1.25.0")]
3042 impl<T: ?Sized> Copy for NonNull<T> { }
3044 #[unstable(feature = "coerce_unsized", issue = "27732")]
3045 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
3047 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
3048 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
3050 #[stable(feature = "nonnull", since = "1.25.0")]
3051 impl<T: ?Sized> fmt::Debug for NonNull<T> {
3052 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3053 fmt::Pointer::fmt(&self.as_ptr(), f)
3057 #[stable(feature = "nonnull", since = "1.25.0")]
3058 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
3059 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3060 fmt::Pointer::fmt(&self.as_ptr(), f)
3064 #[stable(feature = "nonnull", since = "1.25.0")]
3065 impl<T: ?Sized> Eq for NonNull<T> {}
3067 #[stable(feature = "nonnull", since = "1.25.0")]
3068 impl<T: ?Sized> PartialEq for NonNull<T> {
3070 fn eq(&self, other: &Self) -> bool {
3071 self.as_ptr() == other.as_ptr()
3075 #[stable(feature = "nonnull", since = "1.25.0")]
3076 impl<T: ?Sized> Ord for NonNull<T> {
3078 fn cmp(&self, other: &Self) -> Ordering {
3079 self.as_ptr().cmp(&other.as_ptr())
3083 #[stable(feature = "nonnull", since = "1.25.0")]
3084 impl<T: ?Sized> PartialOrd for NonNull<T> {
3086 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3087 self.as_ptr().partial_cmp(&other.as_ptr())
3091 #[stable(feature = "nonnull", since = "1.25.0")]
3092 impl<T: ?Sized> hash::Hash for NonNull<T> {
3094 fn hash<H: hash::Hasher>(&self, state: &mut H) {
3095 self.as_ptr().hash(state)
3099 #[unstable(feature = "ptr_internals", issue = "0")]
3100 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
3102 fn from(unique: Unique<T>) -> Self {
3103 unsafe { NonNull { pointer: unique.pointer } }
3107 #[stable(feature = "nonnull", since = "1.25.0")]
3108 impl<T: ?Sized> From<&mut T> for NonNull<T> {
3110 fn from(reference: &mut T) -> Self {
3111 unsafe { NonNull { pointer: reference as *mut T } }
3115 #[stable(feature = "nonnull", since = "1.25.0")]
3116 impl<T: ?Sized> From<&T> for NonNull<T> {
3118 fn from(reference: &T) -> Self {
3119 unsafe { NonNull { pointer: reference as *const T } }