1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Manually manage memory through raw pointers.
13 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
17 //! Many functions in this module take raw pointers as arguments and read from
18 //! or write to them. For this to be safe, these pointers must be *valid*.
19 //! Whether a pointer is valid depends on the operation it is used for
20 //! (read or write), and the extent of the memory that is accessed (i.e.,
21 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
22 //! to access only a single value, in which case the documentation omits the size
23 //! and implicitly assumes it to be `size_of::<T>()` bytes.
25 //! The precise rules for validity are not determined yet. The guarantees that are
26 //! provided at this point are very minimal:
28 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
29 //! * All pointers (except for the null pointer) are valid for all operations of
31 //! * All accesses performed by functions in this module are *non-atomic* in the sense
32 //! of [atomic operations] used to synchronize between threads. This means it is
33 //! undefined behavior to perform two concurrent accesses to the same location from different
34 //! threads unless both accesses only read from memory. Notice that this explicitly
35 //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
36 //! be used for inter-thread synchronization.
37 //! * The result of casting a reference to a pointer is valid for as long as the
38 //! underlying object is live and no reference (just raw pointers) is used to
39 //! access the same memory.
41 //! These axioms, along with careful use of [`offset`] for pointer arithmentic,
42 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
43 //! will be provided eventually, as the [aliasing] rules are being determined. For more
44 //! information, see the [book] as well as the section in the reference devoted
45 //! to [undefined behavior][ub].
49 //! Valid raw pointers as defined above are not necessarily properly aligned (where
50 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
51 //! aligned to `mem::align_of::<T>()`). However, most functions require their
52 //! arguments to be properly aligned, and will explicitly state
53 //! this requirement in their documentation. Notable exceptions to this are
54 //! [`read_unaligned`] and [`write_unaligned`].
56 //! When a function requires proper alignment, it does so even if the access
57 //! has size 0, i.e., even if memory is not actually touched. Consider using
58 //! [`NonNull::dangling`] in such cases.
60 //! [aliasing]: ../../nomicon/aliasing.html
61 //! [book]: ../../book/second-edition/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
62 //! [ub]: ../../reference/behavior-considered-undefined.html
63 //! [null]: ./fn.null.html
64 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
65 //! [atomic operations]: ../../std/sync/atomic/index.html
66 //! [`copy`]: ../../std/ptr/fn.copy.html
67 //! [`offset`]: ../../std/primitive.pointer.html#method.offset
68 //! [`read_unaligned`]: ./fn.read_unaligned.html
69 //! [`write_unaligned`]: ./fn.write_unaligned.html
70 //! [`read_volatile`]: ./fn.read_volatile.html
71 //! [`write_volatile`]: ./fn.write_volatile.html
72 //! [`NonNull::dangling`]: ./struct.NonNull.html#method.dangling
74 #![stable(feature = "rust1", since = "1.0.0")]
78 use ops::CoerceUnsized;
81 use marker::{PhantomData, Unsize};
85 use cmp::Ordering::{self, Less, Equal, Greater};
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub use intrinsics::copy_nonoverlapping;
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub use intrinsics::copy;
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub use intrinsics::write_bytes;
96 /// Executes the destructor (if any) of the pointed-to value.
98 /// This is semantically equivalent to calling [`ptr::read`] and discarding
99 /// the result, but has the following advantages:
101 /// * It is *required* to use `drop_in_place` to drop unsized types like
102 /// trait objects, because they can't be read out onto the stack and
103 /// dropped normally.
105 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
106 /// dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
107 /// as the compiler doesn't need to prove that it's sound to elide the
110 /// [`ptr::read`]: ../ptr/fn.read.html
114 /// Behavior is undefined if any of the following conditions are violated:
116 /// * `to_drop` must be [valid] for reads.
118 /// * `to_drop` must be properly aligned. See the example below for how to drop
119 /// an unaligned pointer.
121 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
122 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
123 /// foo` counts as a use because it will cause the the value to be dropped
124 /// again. [`write`] can be used to overwrite data without causing it to be
127 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
129 /// [valid]: ../ptr/index.html#safety
130 /// [`Copy`]: ../marker/trait.Copy.html
131 /// [`write`]: ../ptr/fn.write.html
135 /// Manually remove the last item from a vector:
141 /// let last = Rc::new(1);
142 /// let weak = Rc::downgrade(&last);
144 /// let mut v = vec![Rc::new(0), last];
147 /// // Get a raw pointer to the last element in `v`.
148 /// let ptr = &mut v[1] as *mut _;
149 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
150 /// // to prevent issues if the `drop_in_place` below panics.
152 /// // Without a call `drop_in_place`, the last item would never be dropped,
153 /// // and the memory it manages would be leaked.
154 /// ptr::drop_in_place(ptr);
157 /// assert_eq!(v, &[0.into()]);
159 /// // Ensure that the last item was dropped.
160 /// assert!(weak.upgrade().is_none());
163 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
169 /// unsafe fn drop_after_copy<T>(to_drop: *mut T) {
170 /// let mut copy: T = mem::uninitialized();
171 /// ptr::copy(to_drop, &mut copy, 1);
175 /// #[repr(packed, C)]
178 /// unaligned: Vec<i32>,
181 /// let mut p = Packed { _padding: 0, unaligned: vec![42] };
183 /// drop_after_copy(&mut p.unaligned as *mut _);
188 /// Notice that the compiler performs this copy automatically when dropping packed structs,
189 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
191 #[stable(feature = "drop_in_place", since = "1.8.0")]
192 #[lang = "drop_in_place"]
193 #[allow(unconditional_recursion)]
194 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
195 // Code here does not matter - this is replaced by the
196 // real drop glue by the compiler.
197 drop_in_place(to_drop);
200 /// Creates a null raw pointer.
207 /// let p: *const i32 = ptr::null();
208 /// assert!(p.is_null());
211 #[stable(feature = "rust1", since = "1.0.0")]
212 pub const fn null<T>() -> *const T { 0 as *const T }
214 /// Creates a null mutable raw pointer.
221 /// let p: *mut i32 = ptr::null_mut();
222 /// assert!(p.is_null());
225 #[stable(feature = "rust1", since = "1.0.0")]
226 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
228 /// Swaps the values at two mutable locations of the same type, without
229 /// deinitializing either.
231 /// But for the following two exceptions, this function is semantically
232 /// equivalent to [`mem::swap`]:
234 /// * It operates on raw pointers instead of references. When references are
235 /// available, [`mem::swap`] should be preferred.
237 /// * The two pointed-to values may overlap. If the values do overlap, then the
238 /// overlapping region of memory from `x` will be used. This is demonstrated
239 /// in the second example below.
241 /// [`mem::swap`]: ../mem/fn.swap.html
245 /// Behavior is undefined if any of the following conditions are violated:
247 /// * Both `x` and `y` must be [valid] for reads and writes.
249 /// * Both `x` and `y` must be properly aligned.
251 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
253 /// [valid]: ../ptr/index.html#safety
257 /// Swapping two non-overlapping regions:
262 /// let mut array = [0, 1, 2, 3];
264 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
265 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
269 /// assert_eq!([2, 3, 0, 1], array);
273 /// Swapping two overlapping regions:
278 /// let mut array = [0, 1, 2, 3];
280 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
281 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
285 /// // The indices `1..3` of the slice overlap between `x` and `y`.
286 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
287 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
288 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
289 /// // This implementation is defined to make the latter choice.
290 /// assert_eq!([1, 0, 1, 2], array);
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
296 // Give ourselves some scratch space to work with
297 let mut tmp: T = mem::uninitialized();
300 copy_nonoverlapping(x, &mut tmp, 1);
301 copy(y, x, 1); // `x` and `y` may overlap
302 copy_nonoverlapping(&tmp, y, 1);
304 // y and t now point to the same thing, but we need to completely forget `tmp`
305 // because it's no longer relevant.
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: Block = mem::uninitialized();
394 let t = &mut t as *mut _ 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: UnalignedBlock = mem::uninitialized();
411 let t = &mut t as *mut _ 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: T = mem::uninitialized();
577 copy_nonoverlapping(src, &mut tmp, 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 and properly aligned.
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: T = mem::uninitialized();
644 copy_nonoverlapping(src as *const u8,
645 &mut tmp as *mut T 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 and properly aligned.
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 no-ops
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
855 /// Just like in C, whether an operation is volatile has no bearing whatsoever
856 /// on questions involving concurrent access from multiple threads. Volatile
857 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
858 /// a race between a `read_volatile` and any write operation to the same location
859 /// is undefined behavior.
867 /// let y = &x as *const i32;
870 /// assert_eq!(std::ptr::read_volatile(y), 12);
874 #[stable(feature = "volatile", since = "1.9.0")]
875 pub unsafe fn read_volatile<T>(src: *const T) -> T {
876 intrinsics::volatile_load(src)
879 /// Performs a volatile write of a memory location with the given value without
880 /// reading or dropping the old value.
882 /// Volatile operations are intended to act on I/O memory, and are guaranteed
883 /// to not be elided or reordered by the compiler across other volatile
886 /// Memory accessed with [`read_volatile`] or `write_volatile` should not be
887 /// accessed with non-volatile operations.
889 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
890 /// could leak allocations or resources, so care should be taken not to overwrite
891 /// an object that should be dropped.
893 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
894 /// location pointed to by `dst`.
896 /// [`read_volatile`]: ./fn.read_volatile.html
900 /// Rust does not currently have a rigorously and formally defined memory model,
901 /// so the precise semantics of what "volatile" means here is subject to change
902 /// over time. That being said, the semantics will almost always end up pretty
903 /// similar to [C11's definition of volatile][c11].
905 /// The compiler shouldn't change the relative order or number of volatile
906 /// memory operations. However, volatile memory operations on zero-sized types
907 /// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops
908 /// and may be ignored.
910 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
914 /// Behavior is undefined if any of the following conditions are violated:
916 /// * `dst` must be [valid] for writes.
918 /// * `dst` must be properly aligned.
920 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
922 /// [valid]: ../ptr/index.html#safety
924 /// Just like in C, whether an operation is volatile has no bearing whatsoever
925 /// on questions involving concurrent access from multiple threads. Volatile
926 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
927 /// a race between a `write_volatile` and any other operation (reading or writing)
928 /// on the same location is undefined behavior.
936 /// let y = &mut x as *mut i32;
940 /// std::ptr::write_volatile(y, z);
941 /// assert_eq!(std::ptr::read_volatile(y), 12);
945 #[stable(feature = "volatile", since = "1.9.0")]
946 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
947 intrinsics::volatile_store(dst, src);
950 #[lang = "const_ptr"]
951 impl<T: ?Sized> *const T {
952 /// Returns `true` if the pointer is null.
954 /// Note that unsized types have many possible null pointers, as only the
955 /// raw data pointer is considered, not their length, vtable, etc.
956 /// Therefore, two pointers that are null may still not compare equal to
964 /// let s: &str = "Follow the rabbit";
965 /// let ptr: *const u8 = s.as_ptr();
966 /// assert!(!ptr.is_null());
968 #[stable(feature = "rust1", since = "1.0.0")]
970 pub fn is_null(self) -> bool {
971 // Compare via a cast to a thin pointer, so fat pointers are only
972 // considering their "data" part for null-ness.
973 (self as *const u8) == null()
976 /// Returns `None` if the pointer is null, or else returns a reference to
977 /// the value wrapped in `Some`.
981 /// While this method and its mutable counterpart are useful for
982 /// null-safety, it is important to note that this is still an unsafe
983 /// operation because the returned value could be pointing to invalid
986 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
987 /// not necessarily reflect the actual lifetime of the data.
994 /// let ptr: *const u8 = &10u8 as *const u8;
997 /// if let Some(val_back) = ptr.as_ref() {
998 /// println!("We got back the value: {}!", val_back);
1003 /// # Null-unchecked version
1005 /// If you are sure the pointer can never be null and are looking for some kind of
1006 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>, know that you can
1007 /// dereference the pointer directly.
1010 /// let ptr: *const u8 = &10u8 as *const u8;
1013 /// let val_back = &*ptr;
1014 /// println!("We got back the value: {}!", val_back);
1017 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1019 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1027 /// Calculates the offset from a pointer.
1029 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1030 /// offset of `3 * size_of::<T>()` bytes.
1034 /// If any of the following conditions are violated, the result is Undefined
1037 /// * Both the starting and resulting pointer must be either in bounds or one
1038 /// byte past the end of *the same* allocated object.
1040 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1042 /// * The offset being in bounds cannot rely on "wrapping around" the address
1043 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1045 /// The compiler and standard library generally tries to ensure allocations
1046 /// never reach a size where an offset is a concern. For instance, `Vec`
1047 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1048 /// `vec.as_ptr().add(vec.len())` is always safe.
1050 /// Most platforms fundamentally can't even construct such an allocation.
1051 /// For instance, no known 64-bit platform can ever serve a request
1052 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1053 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1054 /// more than `isize::MAX` bytes with things like Physical Address
1055 /// Extension. As such, memory acquired directly from allocators or memory
1056 /// mapped files *may* be too large to handle with this function.
1058 /// Consider using `wrapping_offset` instead if these constraints are
1059 /// difficult to satisfy. The only advantage of this method is that it
1060 /// enables more aggressive compiler optimizations.
1067 /// let s: &str = "123";
1068 /// let ptr: *const u8 = s.as_ptr();
1071 /// println!("{}", *ptr.offset(1) as char);
1072 /// println!("{}", *ptr.offset(2) as char);
1075 #[stable(feature = "rust1", since = "1.0.0")]
1077 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
1078 intrinsics::offset(self, count)
1081 /// Calculates the offset from a pointer using wrapping arithmetic.
1083 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1084 /// offset of `3 * size_of::<T>()` bytes.
1088 /// The resulting pointer does not need to be in bounds, but it is
1089 /// potentially hazardous to dereference (which requires `unsafe`).
1090 /// In particular, the resulting pointer may *not* be used to access a
1091 /// different allocated object than the one `self` points to. In other
1092 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1093 /// *not* the same as `y`, and dereferencing it is undefined behavior
1094 /// unless `x` and `y` point into the same allocated object.
1096 /// Always use `.offset(count)` instead when possible, because `offset`
1097 /// allows the compiler to optimize better. If you need to cross object
1098 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1105 /// // Iterate using a raw pointer in increments of two elements
1106 /// let data = [1u8, 2, 3, 4, 5];
1107 /// let mut ptr: *const u8 = data.as_ptr();
1109 /// let end_rounded_up = ptr.wrapping_offset(6);
1111 /// // This loop prints "1, 3, 5, "
1112 /// while ptr != end_rounded_up {
1114 /// print!("{}, ", *ptr);
1116 /// ptr = ptr.wrapping_offset(step);
1119 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1121 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
1123 intrinsics::arith_offset(self, count)
1127 /// Calculates the distance between two pointers. The returned value is in
1128 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1130 /// This function is the inverse of [`offset`].
1132 /// [`offset`]: #method.offset
1133 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
1137 /// If any of the following conditions are violated, the result is Undefined
1140 /// * Both the starting and other pointer must be either in bounds or one
1141 /// byte past the end of the same allocated object.
1143 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1145 /// * The distance between the pointers, in bytes, must be an exact multiple
1146 /// of the size of `T`.
1148 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1150 /// The compiler and standard library generally try to ensure allocations
1151 /// never reach a size where an offset is a concern. For instance, `Vec`
1152 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1153 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1155 /// Most platforms fundamentally can't even construct such an allocation.
1156 /// For instance, no known 64-bit platform can ever serve a request
1157 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1158 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1159 /// more than `isize::MAX` bytes with things like Physical Address
1160 /// Extension. As such, memory acquired directly from allocators or memory
1161 /// mapped files *may* be too large to handle with this function.
1163 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1164 /// difficult to satisfy. The only advantage of this method is that it
1165 /// enables more aggressive compiler optimizations.
1169 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1176 /// #![feature(ptr_offset_from)]
1179 /// let ptr1: *const i32 = &a[1];
1180 /// let ptr2: *const i32 = &a[3];
1182 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1183 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1184 /// assert_eq!(ptr1.offset(2), ptr2);
1185 /// assert_eq!(ptr2.offset(-2), ptr1);
1188 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1190 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1191 let pointee_size = mem::size_of::<T>();
1192 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1194 // This is the same sequence that Clang emits for pointer subtraction.
1195 // It can be neither `nsw` nor `nuw` because the input is treated as
1196 // unsigned but then the output is treated as signed, so neither works.
1197 let d = isize::wrapping_sub(self as _, origin as _);
1198 intrinsics::exact_div(d, pointee_size as _)
1201 /// Calculates the distance between two pointers. The returned value is in
1202 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1204 /// If the address different between the two pointers is not a multiple of
1205 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1208 /// Though this method is safe for any two pointers, note that its result
1209 /// will be mostly useless if the two pointers aren't into the same allocated
1210 /// object, for example if they point to two different local variables.
1214 /// This function panics if `T` is a zero-sized type.
1221 /// #![feature(ptr_wrapping_offset_from)]
1224 /// let ptr1: *const i32 = &a[1];
1225 /// let ptr2: *const i32 = &a[3];
1226 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1227 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1228 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1229 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1231 /// let ptr1: *const i32 = 3 as _;
1232 /// let ptr2: *const i32 = 13 as _;
1233 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1235 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1237 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1238 let pointee_size = mem::size_of::<T>();
1239 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1241 let d = isize::wrapping_sub(self as _, origin as _);
1242 d.wrapping_div(pointee_size as _)
1245 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1247 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1248 /// offset of `3 * size_of::<T>()` bytes.
1252 /// If any of the following conditions are violated, the result is Undefined
1255 /// * Both the starting and resulting pointer must be either in bounds or one
1256 /// byte past the end of an allocated object.
1258 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1260 /// * The offset being in bounds cannot rely on "wrapping around" the address
1261 /// space. That is, the infinite-precision sum must fit in a `usize`.
1263 /// The compiler and standard library generally tries to ensure allocations
1264 /// never reach a size where an offset is a concern. For instance, `Vec`
1265 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1266 /// `vec.as_ptr().add(vec.len())` is always safe.
1268 /// Most platforms fundamentally can't even construct such an allocation.
1269 /// For instance, no known 64-bit platform can ever serve a request
1270 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1271 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1272 /// more than `isize::MAX` bytes with things like Physical Address
1273 /// Extension. As such, memory acquired directly from allocators or memory
1274 /// mapped files *may* be too large to handle with this function.
1276 /// Consider using `wrapping_offset` instead if these constraints are
1277 /// difficult to satisfy. The only advantage of this method is that it
1278 /// enables more aggressive compiler optimizations.
1285 /// let s: &str = "123";
1286 /// let ptr: *const u8 = s.as_ptr();
1289 /// println!("{}", *ptr.add(1) as char);
1290 /// println!("{}", *ptr.add(2) as char);
1293 #[stable(feature = "pointer_methods", since = "1.26.0")]
1295 pub unsafe fn add(self, count: usize) -> Self
1298 self.offset(count as isize)
1301 /// Calculates the offset from a pointer (convenience for
1302 /// `.offset((count as isize).wrapping_neg())`).
1304 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1305 /// offset of `3 * size_of::<T>()` bytes.
1309 /// If any of the following conditions are violated, the result is Undefined
1312 /// * Both the starting and resulting pointer must be either in bounds or one
1313 /// byte past the end of an allocated object.
1315 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1317 /// * The offset being in bounds cannot rely on "wrapping around" the address
1318 /// space. That is, the infinite-precision sum must fit in a usize.
1320 /// The compiler and standard library generally tries to ensure allocations
1321 /// never reach a size where an offset is a concern. For instance, `Vec`
1322 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1323 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1325 /// Most platforms fundamentally can't even construct such an allocation.
1326 /// For instance, no known 64-bit platform can ever serve a request
1327 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1328 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1329 /// more than `isize::MAX` bytes with things like Physical Address
1330 /// Extension. As such, memory acquired directly from allocators or memory
1331 /// mapped files *may* be too large to handle with this function.
1333 /// Consider using `wrapping_offset` instead if these constraints are
1334 /// difficult to satisfy. The only advantage of this method is that it
1335 /// enables more aggressive compiler optimizations.
1342 /// let s: &str = "123";
1345 /// let end: *const u8 = s.as_ptr().add(3);
1346 /// println!("{}", *end.sub(1) as char);
1347 /// println!("{}", *end.sub(2) as char);
1350 #[stable(feature = "pointer_methods", since = "1.26.0")]
1352 pub unsafe fn sub(self, count: usize) -> Self
1355 self.offset((count as isize).wrapping_neg())
1358 /// Calculates the offset from a pointer using wrapping arithmetic.
1359 /// (convenience for `.wrapping_offset(count as isize)`)
1361 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1362 /// offset of `3 * size_of::<T>()` bytes.
1366 /// The resulting pointer does not need to be in bounds, but it is
1367 /// potentially hazardous to dereference (which requires `unsafe`).
1369 /// Always use `.add(count)` instead when possible, because `add`
1370 /// allows the compiler to optimize better.
1377 /// // Iterate using a raw pointer in increments of two elements
1378 /// let data = [1u8, 2, 3, 4, 5];
1379 /// let mut ptr: *const u8 = data.as_ptr();
1381 /// let end_rounded_up = ptr.wrapping_add(6);
1383 /// // This loop prints "1, 3, 5, "
1384 /// while ptr != end_rounded_up {
1386 /// print!("{}, ", *ptr);
1388 /// ptr = ptr.wrapping_add(step);
1391 #[stable(feature = "pointer_methods", since = "1.26.0")]
1393 pub fn wrapping_add(self, count: usize) -> Self
1396 self.wrapping_offset(count as isize)
1399 /// Calculates the offset from a pointer using wrapping arithmetic.
1400 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1402 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1403 /// offset of `3 * size_of::<T>()` bytes.
1407 /// The resulting pointer does not need to be in bounds, but it is
1408 /// potentially hazardous to dereference (which requires `unsafe`).
1410 /// Always use `.sub(count)` instead when possible, because `sub`
1411 /// allows the compiler to optimize better.
1418 /// // Iterate using a raw pointer in increments of two elements (backwards)
1419 /// let data = [1u8, 2, 3, 4, 5];
1420 /// let mut ptr: *const u8 = data.as_ptr();
1421 /// let start_rounded_down = ptr.wrapping_sub(2);
1422 /// ptr = ptr.wrapping_add(4);
1424 /// // This loop prints "5, 3, 1, "
1425 /// while ptr != start_rounded_down {
1427 /// print!("{}, ", *ptr);
1429 /// ptr = ptr.wrapping_sub(step);
1432 #[stable(feature = "pointer_methods", since = "1.26.0")]
1434 pub fn wrapping_sub(self, count: usize) -> Self
1437 self.wrapping_offset((count as isize).wrapping_neg())
1440 /// Reads the value from `self` without moving it. This leaves the
1441 /// memory in `self` unchanged.
1443 /// See [`ptr::read`] for safety concerns and examples.
1445 /// [`ptr::read`]: ./ptr/fn.read.html
1446 #[stable(feature = "pointer_methods", since = "1.26.0")]
1448 pub unsafe fn read(self) -> T
1454 /// Performs a volatile read of the value from `self` without moving it. This
1455 /// leaves the memory in `self` unchanged.
1457 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1458 /// to not be elided or reordered by the compiler across other volatile
1461 /// See [`ptr::read_volatile`] for safety concerns and examples.
1463 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
1464 #[stable(feature = "pointer_methods", since = "1.26.0")]
1466 pub unsafe fn read_volatile(self) -> T
1472 /// Reads the value from `self` without moving it. This leaves the
1473 /// memory in `self` unchanged.
1475 /// Unlike `read`, the pointer may be unaligned.
1477 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1479 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
1480 #[stable(feature = "pointer_methods", since = "1.26.0")]
1482 pub unsafe fn read_unaligned(self) -> T
1485 read_unaligned(self)
1488 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1489 /// and destination may overlap.
1491 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1493 /// See [`ptr::copy`] for safety concerns and examples.
1495 /// [`ptr::copy`]: ./ptr/fn.copy.html
1496 #[stable(feature = "pointer_methods", since = "1.26.0")]
1498 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1501 copy(self, dest, count)
1504 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1505 /// and destination may *not* overlap.
1507 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1509 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1511 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
1512 #[stable(feature = "pointer_methods", since = "1.26.0")]
1514 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1517 copy_nonoverlapping(self, dest, count)
1520 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1523 /// If it is not possible to align the pointer, the implementation returns
1524 /// `usize::max_value()`.
1526 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1527 /// used with the `offset` or `offset_to` methods.
1529 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
1530 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1531 /// the returned offset is correct in all terms other than alignment.
1535 /// The function panics if `align` is not a power-of-two.
1539 /// Accessing adjacent `u8` as `u16`
1542 /// # #![feature(align_offset)]
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 #[unstable(feature = "align_offset", issue = "44488")]
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 an 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 an 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 /// # #![feature(align_offset)]
2315 /// # fn foo(n: usize) {
2316 /// # use std::mem::align_of;
2318 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
2319 /// let ptr = &x[n] as *const u8;
2320 /// let offset = ptr.align_offset(align_of::<u16>());
2321 /// if offset < x.len() - n - 1 {
2322 /// let u16_ptr = ptr.add(offset) as *const u16;
2323 /// assert_ne!(*u16_ptr, 500);
2325 /// // while the pointer can be aligned via `offset`, it would point
2326 /// // outside the allocation
2330 #[unstable(feature = "align_offset", issue = "44488")]
2331 pub fn align_offset(self, align: usize) -> usize where T: Sized {
2332 if !align.is_power_of_two() {
2333 panic!("align_offset: align is not a power-of-two");
2336 align_offset(self, align)
2341 /// Align pointer `p`.
2343 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
2344 /// to pointer `p` so that pointer `p` would get aligned to `a`.
2346 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
2347 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2350 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2351 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2352 /// than trying to adapt this to accommodate that change.
2354 /// Any questions go to @nagisa.
2355 #[lang="align_offset"]
2356 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2357 /// Calculate multiplicative modular inverse of `x` modulo `m`.
2359 /// This implementation is tailored for align_offset and has following preconditions:
2361 /// * `m` is a power-of-two;
2362 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2364 /// Implementation of this function shall not panic. Ever.
2366 fn mod_inv(x: usize, m: usize) -> usize {
2367 /// Multiplicative modular inverse table modulo 2⁴ = 16.
2369 /// Note, that this table does not contain values where inverse does not exist (i.e. for
2370 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2371 const INV_TABLE_MOD_16: [usize; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2372 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2373 const INV_TABLE_MOD: usize = 16;
2375 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
2377 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1];
2378 if m <= INV_TABLE_MOD {
2379 table_inverse & (m - 1)
2381 // We iterate "up" using the following formula:
2383 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2385 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
2386 let mut inverse = table_inverse;
2387 let mut going_mod = INV_TABLE_MOD_SQUARED;
2389 // y = y * (2 - xy) mod n
2391 // Note, that we use wrapping operations here intentionally – the original formula
2392 // uses e.g. subtraction `mod n`. It is entirely fine to do them `mod
2393 // usize::max_value()` instead, because we take the result `mod n` at the end
2395 inverse = inverse.wrapping_mul(
2396 2usize.wrapping_sub(x.wrapping_mul(inverse))
2397 ) & (going_mod - 1);
2399 return inverse & (m - 1);
2401 going_mod = going_mod.wrapping_mul(going_mod);
2406 let stride = ::mem::size_of::<T>();
2407 let a_minus_one = a.wrapping_sub(1);
2408 let pmoda = p as usize & a_minus_one;
2411 // Already aligned. Yay!
2416 return if stride == 0 {
2417 // If the pointer is not aligned, and the element is zero-sized, then no amount of
2418 // elements will ever align the pointer.
2421 a.wrapping_sub(pmoda)
2425 let smoda = stride & a_minus_one;
2426 // a is power-of-two so cannot be 0. stride = 0 is handled above.
2427 let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
2428 let gcd = 1usize << gcdpow;
2431 // This branch solves for the variable $o$ in following linear congruence equation:
2433 // ⎰ p + o ≡ 0 (mod a) # $p + o$ must be aligned to specified alignment $a$
2434 // ⎱ o ≡ 0 (mod s) # offset $o$ must be a multiple of stride $s$
2438 // * a, s are co-prime
2440 // This gives us the formula below:
2442 // o = (a - (p mod a)) * (s⁻¹ mod a) * s
2444 // The first term is “the relative alignment of p to a”, the second term is “how does
2445 // incrementing p by one s change the relative alignment of p”, the third term is
2446 // translating change in units of s to a byte count.
2448 // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
2449 // to take the result $o mod lcm(s, a)$. Since $s$ and $a$ are co-prime (i.e. $gcd(s, a) =
2450 // 1$) and $lcm(s, a) = s * a / gcd(s, a)$, we can replace $lcm(s, a)$ with just a $s * a$.
2452 // (Author note: we decided later on to express the offset in "elements" rather than bytes,
2453 // which drops the multiplication by `s` on both sides of the modulo.)
2454 return intrinsics::unchecked_rem(a.wrapping_sub(pmoda).wrapping_mul(mod_inv(smoda, a)), a);
2457 if p as usize & (gcd - 1) == 0 {
2458 // This can be aligned, but `a` and `stride` are not co-prime, so a somewhat adapted
2460 let j = a.wrapping_sub(pmoda) >> gcdpow;
2461 let k = smoda >> gcdpow;
2462 return intrinsics::unchecked_rem(j.wrapping_mul(mod_inv(k, a)), a >> gcdpow);
2465 // Cannot be aligned at all.
2471 // Equality for pointers
2472 #[stable(feature = "rust1", since = "1.0.0")]
2473 impl<T: ?Sized> PartialEq for *const T {
2475 fn eq(&self, other: &*const T) -> bool { *self == *other }
2478 #[stable(feature = "rust1", since = "1.0.0")]
2479 impl<T: ?Sized> Eq for *const T {}
2481 #[stable(feature = "rust1", since = "1.0.0")]
2482 impl<T: ?Sized> PartialEq for *mut T {
2484 fn eq(&self, other: &*mut T) -> bool { *self == *other }
2487 #[stable(feature = "rust1", since = "1.0.0")]
2488 impl<T: ?Sized> Eq for *mut T {}
2490 /// Compare raw pointers for equality.
2492 /// This is the same as using the `==` operator, but less generic:
2493 /// the arguments have to be `*const T` raw pointers,
2494 /// not anything that implements `PartialEq`.
2496 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2497 /// by their address rather than comparing the values they point to
2498 /// (which is what the `PartialEq for &T` implementation does).
2506 /// let other_five = 5;
2507 /// let five_ref = &five;
2508 /// let same_five_ref = &five;
2509 /// let other_five_ref = &other_five;
2511 /// assert!(five_ref == same_five_ref);
2512 /// assert!(five_ref == other_five_ref);
2514 /// assert!(ptr::eq(five_ref, same_five_ref));
2515 /// assert!(!ptr::eq(five_ref, other_five_ref));
2517 #[stable(feature = "ptr_eq", since = "1.17.0")]
2519 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2523 // Impls for function pointers
2524 macro_rules! fnptr_impls_safety_abi {
2525 ($FnTy: ty, $($Arg: ident),*) => {
2526 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2527 impl<Ret, $($Arg),*> PartialEq for $FnTy {
2529 fn eq(&self, other: &Self) -> bool {
2530 *self as usize == *other as usize
2534 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2535 impl<Ret, $($Arg),*> Eq for $FnTy {}
2537 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2538 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2540 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2541 (*self as usize).partial_cmp(&(*other as usize))
2545 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2546 impl<Ret, $($Arg),*> Ord for $FnTy {
2548 fn cmp(&self, other: &Self) -> Ordering {
2549 (*self as usize).cmp(&(*other as usize))
2553 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2554 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2555 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2556 state.write_usize(*self as usize)
2560 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2561 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2562 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2563 fmt::Pointer::fmt(&(*self as *const ()), f)
2567 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2568 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2569 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2570 fmt::Pointer::fmt(&(*self as *const ()), f)
2576 macro_rules! fnptr_impls_args {
2577 ($($Arg: ident),+) => {
2578 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2579 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2580 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2581 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2582 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2583 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2586 // No variadic functions with 0 parameters
2587 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2588 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2589 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2590 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2594 fnptr_impls_args! { }
2595 fnptr_impls_args! { A }
2596 fnptr_impls_args! { A, B }
2597 fnptr_impls_args! { A, B, C }
2598 fnptr_impls_args! { A, B, C, D }
2599 fnptr_impls_args! { A, B, C, D, E }
2600 fnptr_impls_args! { A, B, C, D, E, F }
2601 fnptr_impls_args! { A, B, C, D, E, F, G }
2602 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2603 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2604 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2605 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2606 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2608 // Comparison for pointers
2609 #[stable(feature = "rust1", since = "1.0.0")]
2610 impl<T: ?Sized> Ord for *const T {
2612 fn cmp(&self, other: &*const T) -> Ordering {
2615 } else if self == other {
2623 #[stable(feature = "rust1", since = "1.0.0")]
2624 impl<T: ?Sized> PartialOrd for *const T {
2626 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2627 Some(self.cmp(other))
2631 fn lt(&self, other: &*const T) -> bool { *self < *other }
2634 fn le(&self, other: &*const T) -> bool { *self <= *other }
2637 fn gt(&self, other: &*const T) -> bool { *self > *other }
2640 fn ge(&self, other: &*const T) -> bool { *self >= *other }
2643 #[stable(feature = "rust1", since = "1.0.0")]
2644 impl<T: ?Sized> Ord for *mut T {
2646 fn cmp(&self, other: &*mut T) -> Ordering {
2649 } else if self == other {
2657 #[stable(feature = "rust1", since = "1.0.0")]
2658 impl<T: ?Sized> PartialOrd for *mut T {
2660 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2661 Some(self.cmp(other))
2665 fn lt(&self, other: &*mut T) -> bool { *self < *other }
2668 fn le(&self, other: &*mut T) -> bool { *self <= *other }
2671 fn gt(&self, other: &*mut T) -> bool { *self > *other }
2674 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
2677 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
2678 /// of this wrapper owns the referent. Useful for building abstractions like
2679 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
2681 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
2682 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
2683 /// the kind of strong aliasing guarantees an instance of `T` can expect:
2684 /// the referent of the pointer should not be modified without a unique path to
2685 /// its owning Unique.
2687 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
2688 /// consider using `NonNull`, which has weaker semantics.
2690 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2691 /// is never dereferenced. This is so that enums may use this forbidden value
2692 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
2693 /// However the pointer may still dangle if it isn't dereferenced.
2695 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
2696 /// for any type which upholds Unique's aliasing requirements.
2697 #[unstable(feature = "ptr_internals", issue = "0",
2698 reason = "use NonNull instead and consider PhantomData<T> \
2699 (if you also use #[may_dangle]), Send, and/or Sync")]
2701 #[repr(transparent)]
2702 pub struct Unique<T: ?Sized> {
2703 pointer: NonZero<*const T>,
2704 // NOTE: this marker has no consequences for variance, but is necessary
2705 // for dropck to understand that we logically own a `T`.
2707 // For details, see:
2708 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
2709 _marker: PhantomData<T>,
2712 #[unstable(feature = "ptr_internals", issue = "0")]
2713 impl<T: ?Sized> fmt::Debug for Unique<T> {
2714 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2715 fmt::Pointer::fmt(&self.as_ptr(), f)
2719 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
2720 /// reference is unaliased. Note that this aliasing invariant is
2721 /// unenforced by the type system; the abstraction using the
2722 /// `Unique` must enforce it.
2723 #[unstable(feature = "ptr_internals", issue = "0")]
2724 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
2726 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
2727 /// reference is unaliased. Note that this aliasing invariant is
2728 /// unenforced by the type system; the abstraction using the
2729 /// `Unique` must enforce it.
2730 #[unstable(feature = "ptr_internals", issue = "0")]
2731 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
2733 #[unstable(feature = "ptr_internals", issue = "0")]
2734 impl<T: Sized> Unique<T> {
2735 /// Creates a new `Unique` that is dangling, but well-aligned.
2737 /// This is useful for initializing types which lazily allocate, like
2738 /// `Vec::new` does.
2740 /// Note that the pointer value may potentially represent a valid pointer to
2741 /// a `T`, which means this must not be used as a "not yet initialized"
2742 /// sentinel value. Types that lazily allocate must track initialization by
2743 /// some other means.
2744 // FIXME: rename to dangling() to match NonNull?
2745 pub const fn empty() -> Self {
2747 Unique::new_unchecked(mem::align_of::<T>() as *mut T)
2752 #[unstable(feature = "ptr_internals", issue = "0")]
2753 impl<T: ?Sized> Unique<T> {
2754 /// Creates a new `Unique`.
2758 /// `ptr` must be non-null.
2759 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2760 Unique { pointer: NonZero(ptr as _), _marker: PhantomData }
2763 /// Creates a new `Unique` if `ptr` is non-null.
2764 pub fn new(ptr: *mut T) -> Option<Self> {
2766 Some(Unique { pointer: NonZero(ptr as _), _marker: PhantomData })
2772 /// Acquires the underlying `*mut` pointer.
2773 pub fn as_ptr(self) -> *mut T {
2774 self.pointer.0 as *mut T
2777 /// Dereferences the content.
2779 /// The resulting lifetime is bound to self so this behaves "as if"
2780 /// it were actually an instance of T that is getting borrowed. If a longer
2781 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2782 pub unsafe fn as_ref(&self) -> &T {
2786 /// Mutably dereferences the content.
2788 /// The resulting lifetime is bound to self so this behaves "as if"
2789 /// it were actually an instance of T that is getting borrowed. If a longer
2790 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2791 pub unsafe fn as_mut(&mut self) -> &mut T {
2796 #[unstable(feature = "ptr_internals", issue = "0")]
2797 impl<T: ?Sized> Clone for Unique<T> {
2798 fn clone(&self) -> Self {
2803 #[unstable(feature = "ptr_internals", issue = "0")]
2804 impl<T: ?Sized> Copy for Unique<T> { }
2806 #[unstable(feature = "ptr_internals", issue = "0")]
2807 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
2809 #[unstable(feature = "ptr_internals", issue = "0")]
2810 impl<T: ?Sized> fmt::Pointer for Unique<T> {
2811 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2812 fmt::Pointer::fmt(&self.as_ptr(), f)
2816 #[unstable(feature = "ptr_internals", issue = "0")]
2817 impl<'a, T: ?Sized> From<&'a mut T> for Unique<T> {
2818 fn from(reference: &'a mut T) -> Self {
2819 Unique { pointer: NonZero(reference as _), _marker: PhantomData }
2823 #[unstable(feature = "ptr_internals", issue = "0")]
2824 impl<'a, T: ?Sized> From<&'a T> for Unique<T> {
2825 fn from(reference: &'a T) -> Self {
2826 Unique { pointer: NonZero(reference as _), _marker: PhantomData }
2830 #[unstable(feature = "ptr_internals", issue = "0")]
2831 impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
2832 fn from(p: NonNull<T>) -> Self {
2833 Unique { pointer: p.pointer, _marker: PhantomData }
2837 /// `*mut T` but non-zero and covariant.
2839 /// This is often the correct thing to use when building data structures using
2840 /// raw pointers, but is ultimately more dangerous to use because of its additional
2841 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
2843 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2844 /// is never dereferenced. This is so that enums may use this forbidden value
2845 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
2846 /// However the pointer may still dangle if it isn't dereferenced.
2848 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
2849 /// for your use case, you should include some PhantomData in your type to
2850 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
2851 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
2852 /// such as Box, Rc, Arc, Vec, and LinkedList. This is the case because they
2853 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
2854 #[stable(feature = "nonnull", since = "1.25.0")]
2855 #[repr(transparent)]
2856 pub struct NonNull<T: ?Sized> {
2857 pointer: NonZero<*const T>,
2860 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
2861 // NB: This impl is unnecessary, but should provide better error messages.
2862 #[stable(feature = "nonnull", since = "1.25.0")]
2863 impl<T: ?Sized> !Send for NonNull<T> { }
2865 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
2866 // NB: This impl is unnecessary, but should provide better error messages.
2867 #[stable(feature = "nonnull", since = "1.25.0")]
2868 impl<T: ?Sized> !Sync for NonNull<T> { }
2870 impl<T: Sized> NonNull<T> {
2871 /// Creates a new `NonNull` that is dangling, but well-aligned.
2873 /// This is useful for initializing types which lazily allocate, like
2874 /// `Vec::new` does.
2876 /// Note that the pointer value may potentially represent a valid pointer to
2877 /// a `T`, which means this must not be used as a "not yet initialized"
2878 /// sentinel value. Types that lazily allocate must track initialization by
2879 /// some other means.
2880 #[stable(feature = "nonnull", since = "1.25.0")]
2881 pub fn dangling() -> Self {
2883 let ptr = mem::align_of::<T>() as *mut T;
2884 NonNull::new_unchecked(ptr)
2889 impl<T: ?Sized> NonNull<T> {
2890 /// Creates a new `NonNull`.
2894 /// `ptr` must be non-null.
2895 #[stable(feature = "nonnull", since = "1.25.0")]
2896 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
2897 NonNull { pointer: NonZero(ptr as _) }
2900 /// Creates a new `NonNull` if `ptr` is non-null.
2901 #[stable(feature = "nonnull", since = "1.25.0")]
2902 pub fn new(ptr: *mut T) -> Option<Self> {
2904 Some(NonNull { pointer: NonZero(ptr as _) })
2910 /// Acquires the underlying `*mut` pointer.
2911 #[stable(feature = "nonnull", since = "1.25.0")]
2912 pub fn as_ptr(self) -> *mut T {
2913 self.pointer.0 as *mut T
2916 /// Dereferences the content.
2918 /// The resulting lifetime is bound to self so this behaves "as if"
2919 /// it were actually an instance of T that is getting borrowed. If a longer
2920 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
2921 #[stable(feature = "nonnull", since = "1.25.0")]
2922 pub unsafe fn as_ref(&self) -> &T {
2926 /// Mutably dereferences the content.
2928 /// The resulting lifetime is bound to self so this behaves "as if"
2929 /// it were actually an instance of T that is getting borrowed. If a longer
2930 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
2931 #[stable(feature = "nonnull", since = "1.25.0")]
2932 pub unsafe fn as_mut(&mut self) -> &mut T {
2936 /// Cast to a pointer of another type
2937 #[stable(feature = "nonnull_cast", since = "1.27.0")]
2938 pub fn cast<U>(self) -> NonNull<U> {
2940 NonNull::new_unchecked(self.as_ptr() as *mut U)
2945 #[stable(feature = "nonnull", since = "1.25.0")]
2946 impl<T: ?Sized> Clone for NonNull<T> {
2947 fn clone(&self) -> Self {
2952 #[stable(feature = "nonnull", since = "1.25.0")]
2953 impl<T: ?Sized> Copy for NonNull<T> { }
2955 #[unstable(feature = "coerce_unsized", issue = "27732")]
2956 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
2958 #[stable(feature = "nonnull", since = "1.25.0")]
2959 impl<T: ?Sized> fmt::Debug for NonNull<T> {
2960 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2961 fmt::Pointer::fmt(&self.as_ptr(), f)
2965 #[stable(feature = "nonnull", since = "1.25.0")]
2966 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
2967 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2968 fmt::Pointer::fmt(&self.as_ptr(), f)
2972 #[stable(feature = "nonnull", since = "1.25.0")]
2973 impl<T: ?Sized> Eq for NonNull<T> {}
2975 #[stable(feature = "nonnull", since = "1.25.0")]
2976 impl<T: ?Sized> PartialEq for NonNull<T> {
2977 fn eq(&self, other: &Self) -> bool {
2978 self.as_ptr() == other.as_ptr()
2982 #[stable(feature = "nonnull", since = "1.25.0")]
2983 impl<T: ?Sized> Ord for NonNull<T> {
2984 fn cmp(&self, other: &Self) -> Ordering {
2985 self.as_ptr().cmp(&other.as_ptr())
2989 #[stable(feature = "nonnull", since = "1.25.0")]
2990 impl<T: ?Sized> PartialOrd for NonNull<T> {
2991 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2992 self.as_ptr().partial_cmp(&other.as_ptr())
2996 #[stable(feature = "nonnull", since = "1.25.0")]
2997 impl<T: ?Sized> hash::Hash for NonNull<T> {
2998 fn hash<H: hash::Hasher>(&self, state: &mut H) {
2999 self.as_ptr().hash(state)
3003 #[unstable(feature = "ptr_internals", issue = "0")]
3004 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
3005 fn from(unique: Unique<T>) -> Self {
3006 NonNull { pointer: unique.pointer }
3010 #[stable(feature = "nonnull", since = "1.25.0")]
3011 impl<'a, T: ?Sized> From<&'a mut T> for NonNull<T> {
3012 fn from(reference: &'a mut T) -> Self {
3013 NonNull { pointer: NonZero(reference as _) }
3017 #[stable(feature = "nonnull", since = "1.25.0")]
3018 impl<'a, T: ?Sized> From<&'a T> for NonNull<T> {
3019 fn from(reference: &'a T) -> Self {
3020 NonNull { pointer: NonZero(reference as _) }