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 // FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory
13 //! Manually manage memory through raw pointers.
15 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
19 //! Many functions in this module take raw pointers as arguments and dereference
20 //! them. For this to be safe, these pointers must be valid. A valid pointer
21 //! is one that satisfies **all** of the following conditions:
23 //! * The pointer is not null.
24 //! * The pointer is not dangling (it does not point to memory which has been
26 //! * The pointer satisfies [LLVM's pointer aliasing rules].
28 //! Valid pointers are not necessarily properly aligned. However, except for
29 //! [`read_unaligned`] and [`write_unaligned`], most functions require their
30 //! arguments to be aligned. Any alignment requirements will be explicitly
31 //! stated in the function's documentation.
33 //! [LLVM's pointer aliasing rules]: https://llvm.org/docs/LangRef.html#pointer-aliasing-rules
34 //! [`read_unaligned`]: ./fn.read_unaligned.html
35 //! [`write_unaligned`]: ./fn.write_unaligned.html
37 #![stable(feature = "rust1", since = "1.0.0")]
41 use ops::CoerceUnsized;
44 use marker::{PhantomData, Unsize};
48 use cmp::Ordering::{self, Less, Equal, Greater};
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub use intrinsics::copy_nonoverlapping;
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub use intrinsics::copy;
56 #[stable(feature = "rust1", since = "1.0.0")]
57 pub use intrinsics::write_bytes;
59 /// Executes the destructor (if any) of the pointed-to value.
61 /// This is semantically equivalent to calling [`ptr::read`] and discarding
62 /// the result, but has the following advantages:
64 /// * It is *required* to use `drop_in_place` to drop unsized types like
65 /// trait objects, because they can't be read out onto the stack and
68 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
69 /// dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
70 /// as the compiler doesn't need to prove that it's sound to elide the
73 /// [`ptr::read`]: ../ptr/fn.read.html
77 /// Behavior is undefined if any of the following conditions are violated:
79 /// * `to_drop` must be [valid].
81 /// * `to_drop` must be properly aligned.
83 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
84 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
85 /// foo` counts as a use because it will cause the the value to be dropped
86 /// again. [`write`] can be used to overwrite data without causing it to be
89 /// [valid]: ../ptr/index.html#safety
90 /// [`Copy`]: ../marker/trait.Copy.html
91 /// [`write`]: ../ptr/fn.write.html
95 /// Manually remove the last item from a vector:
101 /// let last = Rc::new(1);
102 /// let weak = Rc::downgrade(&last);
104 /// let mut v = vec![Rc::new(0), last];
107 /// // Without a call `drop_in_place`, the last item would never be dropped,
108 /// // and the memory it manages would be leaked.
109 /// ptr::drop_in_place(&mut v[1]);
113 /// assert_eq!(v, &[0.into()]);
115 /// // Ensure that the last item was dropped.
116 /// assert!(weak.upgrade().is_none());
118 #[stable(feature = "drop_in_place", since = "1.8.0")]
119 #[lang = "drop_in_place"]
120 #[allow(unconditional_recursion)]
121 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
122 // Code here does not matter - this is replaced by the
123 // real drop glue by the compiler.
124 drop_in_place(to_drop);
127 /// Creates a null raw pointer.
134 /// let p: *const i32 = ptr::null();
135 /// assert!(p.is_null());
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub const fn null<T>() -> *const T { 0 as *const T }
141 /// Creates a null mutable raw pointer.
148 /// let p: *mut i32 = ptr::null_mut();
149 /// assert!(p.is_null());
152 #[stable(feature = "rust1", since = "1.0.0")]
153 pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
155 /// Swaps the values at two mutable locations of the same type, without
156 /// deinitializing either.
158 /// But for the following two exceptions, this function is semantically
159 /// equivalent to [`mem::swap`]:
161 /// * It operates on raw pointers instead of references. When references are
162 /// available, [`mem::swap`] should be preferred.
164 /// * The two pointed-to values may overlap. If the values do overlap, then the
165 /// overlapping region of memory from `x` will be used. This is demonstrated
166 /// in the examples below.
168 /// [`mem::swap`]: ../mem/fn.swap.html
172 /// Behavior is undefined if any of the following conditions are violated:
174 /// * Both `x` and `y` must be [valid].
176 /// * Both `x` and `y` must be properly aligned.
178 /// [valid]: ../ptr/index.html#safety
182 /// Swapping two non-overlapping regions:
187 /// let mut array = [0, 1, 2, 3];
189 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2];
190 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2];
194 /// assert_eq!([2, 3, 0, 1], array);
198 /// Swapping two overlapping regions:
203 /// let mut array = [0, 1, 2, 3];
205 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3];
206 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3];
210 /// assert_eq!([1, 0, 1, 2], array);
214 #[stable(feature = "rust1", since = "1.0.0")]
215 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
216 // Give ourselves some scratch space to work with
217 let mut tmp: T = mem::uninitialized();
220 copy_nonoverlapping(x, &mut tmp, 1);
221 copy(y, x, 1); // `x` and `y` may overlap
222 copy_nonoverlapping(&tmp, y, 1);
224 // y and t now point to the same thing, but we need to completely forget `tmp`
225 // because it's no longer relevant.
229 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
230 /// beginning at `x` and `y`. The two regions must *not* overlap.
234 /// Behavior is undefined if any of the following conditions are violated:
236 /// * Both `x` and `y` must be [valid].
238 /// * Both `x` and `y` must be properly aligned.
240 /// * `x.offset(count)` must be [valid]. In other words, the region of memory
241 /// which begins at `x` and has a length of `count * size_of::<T>()` bytes
242 /// must belong to a single, live allocation.
244 /// * `y.offset(count)` must be [valid]. In other words, the region of memory
245 /// which begins at `y` and has a length of `count * size_of::<T>()` bytes
246 /// must belong to a single, live allocation.
248 /// * The two regions of memory must *not* overlap.
250 /// [valid]: ../ptr/index.html#safety
259 /// let mut x = [1, 2, 3, 4];
260 /// let mut y = [7, 8, 9];
263 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
266 /// assert_eq!(x, [7, 8, 3, 4]);
267 /// assert_eq!(y, [1, 2, 9]);
270 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
271 pub unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
272 let x = x as *mut u8;
273 let y = y as *mut u8;
274 let len = mem::size_of::<T>() * count;
275 swap_nonoverlapping_bytes(x, y, len)
279 pub(crate) unsafe fn swap_nonoverlapping_one<T>(x: *mut T, y: *mut T) {
280 // For types smaller than the block optimization below,
281 // just swap directly to avoid pessimizing codegen.
282 if mem::size_of::<T>() < 32 {
284 copy_nonoverlapping(y, x, 1);
287 swap_nonoverlapping(x, y, 1);
292 unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) {
293 // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
294 // that swapping either 32 bytes or 64 bytes at a time is most efficient for intel
295 // Haswell E processors. LLVM is more able to optimize if we give a struct a
296 // #[repr(simd)], even if we don't actually use this struct directly.
298 // FIXME repr(simd) broken on emscripten and redox
299 // It's also broken on big-endian powerpc64 and s390x. #42778
300 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox",
301 target_endian = "big")),
303 struct Block(u64, u64, u64, u64);
304 struct UnalignedBlock(u64, u64, u64, u64);
306 let block_size = mem::size_of::<Block>();
308 // Loop through x & y, copying them `Block` at a time
309 // The optimizer should unroll the loop fully for most types
310 // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
312 while i + block_size <= len {
313 // Create some uninitialized memory as scratch space
314 // Declaring `t` here avoids aligning the stack when this loop is unused
315 let mut t: Block = mem::uninitialized();
316 let t = &mut t as *mut _ as *mut u8;
320 // Swap a block of bytes of x & y, using t as a temporary buffer
321 // This should be optimized into efficient SIMD operations where available
322 copy_nonoverlapping(x, t, block_size);
323 copy_nonoverlapping(y, x, block_size);
324 copy_nonoverlapping(t, y, block_size);
329 // Swap any remaining bytes
330 let mut t: UnalignedBlock = mem::uninitialized();
333 let t = &mut t as *mut _ as *mut u8;
337 copy_nonoverlapping(x, t, rem);
338 copy_nonoverlapping(y, x, rem);
339 copy_nonoverlapping(t, y, rem);
343 /// Moves `src` into the pointed `dest`, returning the previous `dest` value.
345 /// Neither value is dropped.
347 /// This function is semantically equivalent to [`mem::replace`] except that it
348 /// operates on raw pointers instead of references. When references are
349 /// available, [`mem::replace`] should be preferred.
351 /// [`mem::replace`]: ../mem/fn.replace.html
355 /// Behavior is undefined if any of the following conditions are violated:
357 /// * `dest` must be [valid].
359 /// * `dest` must be properly aligned.
361 /// [valid]: ../ptr/index.html#safety
368 /// let mut rust = vec!['b', 'u', 's', 't'];
370 /// // `mem::replace` would have the same effect without requiring the unsafe
373 /// ptr::replace(&mut rust[0], 'r')
376 /// assert_eq!(b, 'b');
377 /// assert_eq!(rust, &['r', 'u', 's', 't']);
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
382 mem::swap(&mut *dest, &mut src); // cannot overlap
386 /// Reads the value from `src` without moving it. This leaves the
387 /// memory in `src` unchanged.
391 /// Behavior is undefined if any of the following conditions are violated:
393 /// * `src` must be [valid].
395 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
398 /// ## Ownership of the Returned Value
400 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
401 /// If `T` is not [`Copy`], using both the returned value and the value at
402 /// `*src` can violate memory safety. Note that assigning to `src` counts as a
403 /// use because it will attempt to drop the value at `*src`.
405 /// [`write`] can be used to overwrite data without causing it to be dropped.
407 /// [valid]: ../ptr/index.html#safety
408 /// [`Copy`]: ../marker/trait.Copy.html
409 /// [`read_unaligned`]: ./fn.read_unaligned.html
410 /// [`write`]: ./fn.write.html
415 /// let mut s = String::from("foo");
417 /// // `s2` now points to the same underlying memory as `s1`.
418 /// let mut s2 = ptr::read(&s);
420 /// assert_eq!(s2, "foo");
422 /// // Assigning to `s2` causes its original value to be dropped. Beyond
423 /// // this point, `s` must no longer be used, as the underlying memory has
425 /// s2 = String::default();
426 /// assert_eq!(s2, "");
428 /// // Assigning to `s` would cause the old value to be dropped again,
429 /// // resulting in undefined behavior.
430 /// // s = String::from("bar"); // ERROR
432 /// // `ptr::write` can be used to overwrite a value without dropping it.
433 /// ptr::write(&mut s, String::from("bar"));
436 /// assert_eq!(s, "bar");
445 /// let y = &x as *const i32;
448 /// assert_eq!(std::ptr::read(y), 12);
452 /// Manually implement [`mem::swap`]:
457 /// fn swap<T>(a: &mut T, b: &mut T) {
459 /// // Create a bitwise copy of the value at `a` in `tmp`.
460 /// let tmp = ptr::read(a);
462 /// // Exiting at this point (either by explicitly returning or by
463 /// // calling a function which panics) would cause the value in `tmp` to
464 /// // be dropped while the same value is still referenced by `a`. This
465 /// // could trigger undefined behavior if `T` is not `Copy`.
467 /// // Create a bitwise copy of the value at `b` in `a`.
468 /// // This is safe because mutable references cannot alias.
469 /// ptr::copy_nonoverlapping(b, a, 1);
471 /// // As above, exiting here could trigger undefined behavior because
472 /// // the same value is referenced by `a` and `b`.
474 /// // Move `tmp` into `b`.
475 /// ptr::write(b, tmp);
479 /// let mut foo = "foo".to_owned();
480 /// let mut bar = "bar".to_owned();
482 /// swap(&mut foo, &mut bar);
484 /// assert_eq!(foo, "bar");
485 /// assert_eq!(bar, "foo");
488 /// [`mem::swap`]: ../mem/fn.swap.html
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub unsafe fn read<T>(src: *const T) -> T {
492 let mut tmp: T = mem::uninitialized();
493 copy_nonoverlapping(src, &mut tmp, 1);
497 /// Reads the value from `src` without moving it. This leaves the
498 /// memory in `src` unchanged.
500 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
504 /// Behavior is undefined if any of the following conditions are violated:
506 /// * `src` must be [valid].
508 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
509 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
510 /// value and the value at `*src` can [violate memory safety][read-ownership].
512 /// [`Copy`]: ../marker/trait.Copy.html
513 /// [`read`]: ./fn.read.html
514 /// [`write_unaligned`]: ./fn.write_unaligned.html
515 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
516 /// [valid]: ../ptr/index.html#safety
520 /// Access members of a packed struct by reference:
525 /// #[repr(packed, C)]
526 /// #[derive(Default)]
534 /// unaligned: 0x01020304,
538 /// // Take a reference to a 32-bit integer which is not aligned.
539 /// let unaligned = &x.unaligned;
541 /// // Dereferencing normally will emit an unaligned load instruction,
542 /// // causing undefined behavior.
543 /// // let v = *unaligned; // ERROR
545 /// // Instead, use `read_unaligned` to read improperly aligned values.
546 /// let v = ptr::read_unaligned(unaligned);
551 /// // Accessing unaligned values directly is safe.
552 /// assert!(x.unaligned == v);
555 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
556 pub unsafe fn read_unaligned<T>(src: *const T) -> T {
557 let mut tmp: T = mem::uninitialized();
558 copy_nonoverlapping(src as *const u8,
559 &mut tmp as *mut T as *mut u8,
560 mem::size_of::<T>());
564 /// Overwrites a memory location with the given value without reading or
565 /// dropping the old value.
567 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
568 /// allocations or resources, so care must be taken not to overwrite an object
569 /// that should be dropped.
571 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
572 /// location pointed to by `dst`.
574 /// This is appropriate for initializing uninitialized memory, or overwriting
575 /// memory that has previously been [`read`] from.
577 /// [`read`]: ./fn.read.html
581 /// Behavior is undefined if any of the following conditions are violated:
583 /// * `dst` must be [valid].
585 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
588 /// [valid]: ../ptr/index.html#safety
589 /// [`write_unaligned`]: ./fn.write_unaligned.html
597 /// let y = &mut x as *mut i32;
601 /// std::ptr::write(y, z);
602 /// assert_eq!(std::ptr::read(y), 12);
606 /// Manually implement [`mem::swap`]:
611 /// fn swap<T>(a: &mut T, b: &mut T) {
613 /// let tmp = ptr::read(a);
614 /// ptr::copy_nonoverlapping(b, a, 1);
615 /// ptr::write(b, tmp);
619 /// let mut foo = "foo".to_owned();
620 /// let mut bar = "bar".to_owned();
622 /// swap(&mut foo, &mut bar);
624 /// assert_eq!(foo, "bar");
625 /// assert_eq!(bar, "foo");
628 /// [`mem::swap`]: ../mem/fn.swap.html
630 #[stable(feature = "rust1", since = "1.0.0")]
631 pub unsafe fn write<T>(dst: *mut T, src: T) {
632 intrinsics::move_val_init(&mut *dst, src)
635 /// Overwrites a memory location with the given value without reading or
636 /// dropping the old value.
638 /// Unlike [`write`], the pointer may be unaligned.
640 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
641 /// could leak allocations or resources, so care must be taken not to overwrite
642 /// an object that should be dropped.
644 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
645 /// location pointed to by `dst`.
647 /// This is appropriate for initializing uninitialized memory, or overwriting
648 /// memory that has previously been read with [`read_unaligned`].
650 /// [`write`]: ./fn.write.html
651 /// [`read_unaligned`]: ./fn.read_unaligned.html
655 /// Behavior is undefined if any of the following conditions are violated:
657 /// * `dst` must be [valid].
659 /// [valid]: ../ptr/index.html#safety
663 /// Access fields in a packed struct:
666 /// use std::{mem, ptr};
668 /// #[repr(packed, C)]
669 /// #[derive(Default)]
675 /// let v = 0x01020304;
676 /// let mut x: Packed = unsafe { mem::zeroed() };
679 /// // Take a reference to a 32-bit integer which is not aligned.
680 /// let unaligned = &mut x.unaligned;
682 /// // Dereferencing normally will emit an unaligned store instruction,
683 /// // causing undefined behavior.
684 /// // *unaligned = v; // ERROR
686 /// // Instead, use `write_unaligned` to write improperly aligned values.
687 /// ptr::write_unaligned(unaligned, v);
690 /// // Accessing unaligned values directly is safe.
691 /// assert!(x.unaligned == v);
694 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
695 pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
696 copy_nonoverlapping(&src as *const T as *const u8,
698 mem::size_of::<T>());
702 /// Performs a volatile read of the value from `src` without moving it. This
703 /// leaves the memory in `src` unchanged.
705 /// Volatile operations are intended to act on I/O memory, and are guaranteed
706 /// to not be elided or reordered by the compiler across other volatile
709 /// Memory read with `read_volatile` should almost always be written to using
710 /// [`write_volatile`].
712 /// [`write_volatile`]: ./fn.write_volatile.html
716 /// Rust does not currently have a rigorously and formally defined memory model,
717 /// so the precise semantics of what "volatile" means here is subject to change
718 /// over time. That being said, the semantics will almost always end up pretty
719 /// similar to [C11's definition of volatile][c11].
721 /// The compiler shouldn't change the relative order or number of volatile
722 /// memory operations. However, volatile memory operations on zero-sized types
723 /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
724 /// and may be ignored.
726 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
730 /// Behavior is undefined if any of the following conditions are violated:
732 /// * `src` must be [valid].
734 /// * `src` must be properly aligned.
736 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
737 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
738 /// value and the value at `*src` can [violate memory safety][read-ownership].
739 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
742 /// [valid]: ../ptr/index.html#safety
743 /// [`Copy`]: ../marker/trait.Copy.html
744 /// [`read`]: ./fn.read.html
746 /// Just like in C, whether an operation is volatile has no bearing whatsoever
747 /// on questions involving concurrent access from multiple threads. Volatile
748 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
749 /// a race between a `read_volatile` and any write operation to the same location
750 /// is undefined behavior.
758 /// let y = &x as *const i32;
761 /// assert_eq!(std::ptr::read_volatile(y), 12);
765 #[stable(feature = "volatile", since = "1.9.0")]
766 pub unsafe fn read_volatile<T>(src: *const T) -> T {
767 intrinsics::volatile_load(src)
770 /// Performs a volatile write of a memory location with the given value without
771 /// reading or dropping the old value.
773 /// Volatile operations are intended to act on I/O memory, and are guaranteed
774 /// to not be elided or reordered by the compiler across other volatile
777 /// Memory written with `write_volatile` should almost always be read from using
778 /// [`read_volatile`].
780 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
781 /// could leak allocations or resources, so care must be taken not to overwrite
782 /// an object that should be dropped.
784 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
785 /// location pointed to by `dst`.
787 /// [`read_volatile`]: ./fn.read_volatile.html
791 /// Rust does not currently have a rigorously and formally defined memory model,
792 /// so the precise semantics of what "volatile" means here is subject to change
793 /// over time. That being said, the semantics will almost always end up pretty
794 /// similar to [C11's definition of volatile][c11].
796 /// The compiler shouldn't change the relative order or number of volatile
797 /// memory operations. However, volatile memory operations on zero-sized types
798 /// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops
799 /// and may be ignored.
801 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
805 /// Behavior is undefined if any of the following conditions are violated:
807 /// * `dst` must be [valid].
809 /// * `dst` must be properly aligned.
811 /// [valid]: ../ptr/index.html#safety
813 /// Just like in C, whether an operation is volatile has no bearing whatsoever
814 /// on questions involving concurrent access from multiple threads. Volatile
815 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
816 /// a race between a `write_volatile` and any other operation (reading or writing)
817 /// on the same location is undefined behavior.
825 /// let y = &mut x as *mut i32;
829 /// std::ptr::write_volatile(y, z);
830 /// assert_eq!(std::ptr::read_volatile(y), 12);
834 #[stable(feature = "volatile", since = "1.9.0")]
835 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
836 intrinsics::volatile_store(dst, src);
839 #[lang = "const_ptr"]
840 impl<T: ?Sized> *const T {
841 /// Returns `true` if the pointer is null.
843 /// Note that unsized types have many possible null pointers, as only the
844 /// raw data pointer is considered, not their length, vtable, etc.
845 /// Therefore, two pointers that are null may still not compare equal to
853 /// let s: &str = "Follow the rabbit";
854 /// let ptr: *const u8 = s.as_ptr();
855 /// assert!(!ptr.is_null());
857 #[stable(feature = "rust1", since = "1.0.0")]
859 pub fn is_null(self) -> bool {
860 // Compare via a cast to a thin pointer, so fat pointers are only
861 // considering their "data" part for null-ness.
862 (self as *const u8) == null()
865 /// Returns `None` if the pointer is null, or else returns a reference to
866 /// the value wrapped in `Some`.
870 /// While this method and its mutable counterpart are useful for
871 /// null-safety, it is important to note that this is still an unsafe
872 /// operation because the returned value could be pointing to invalid
875 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
876 /// not necessarily reflect the actual lifetime of the data.
883 /// let ptr: *const u8 = &10u8 as *const u8;
886 /// if let Some(val_back) = ptr.as_ref() {
887 /// println!("We got back the value: {}!", val_back);
892 /// # Null-unchecked version
894 /// If you are sure the pointer can never be null and are looking for some kind of
895 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>, know that you can
896 /// dereference the pointer directly.
899 /// let ptr: *const u8 = &10u8 as *const u8;
902 /// let val_back = &*ptr;
903 /// println!("We got back the value: {}!", val_back);
906 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
908 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
916 /// Calculates the offset from a pointer.
918 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
919 /// offset of `3 * size_of::<T>()` bytes.
923 /// If any of the following conditions are violated, the result is Undefined
926 /// * Both the starting and resulting pointer must be either in bounds or one
927 /// byte past the end of *the same* allocated object.
929 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
931 /// * The offset being in bounds cannot rely on "wrapping around" the address
932 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
934 /// The compiler and standard library generally tries to ensure allocations
935 /// never reach a size where an offset is a concern. For instance, `Vec`
936 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
937 /// `vec.as_ptr().add(vec.len())` is always safe.
939 /// Most platforms fundamentally can't even construct such an allocation.
940 /// For instance, no known 64-bit platform can ever serve a request
941 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
942 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
943 /// more than `isize::MAX` bytes with things like Physical Address
944 /// Extension. As such, memory acquired directly from allocators or memory
945 /// mapped files *may* be too large to handle with this function.
947 /// Consider using `wrapping_offset` instead if these constraints are
948 /// difficult to satisfy. The only advantage of this method is that it
949 /// enables more aggressive compiler optimizations.
956 /// let s: &str = "123";
957 /// let ptr: *const u8 = s.as_ptr();
960 /// println!("{}", *ptr.offset(1) as char);
961 /// println!("{}", *ptr.offset(2) as char);
964 #[stable(feature = "rust1", since = "1.0.0")]
966 pub unsafe fn offset(self, count: isize) -> *const T where T: Sized {
967 intrinsics::offset(self, count)
970 /// Calculates the offset from a pointer using wrapping arithmetic.
972 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
973 /// offset of `3 * size_of::<T>()` bytes.
977 /// The resulting pointer does not need to be in bounds, but it is
978 /// potentially hazardous to dereference (which requires `unsafe`).
979 /// In particular, the resulting pointer may *not* be used to access a
980 /// different allocated object than the one `self` points to. In other
981 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
982 /// *not* the same as `y`, and dereferencing it is undefined behavior
983 /// unless `x` and `y` point into the same allocated object.
985 /// Always use `.offset(count)` instead when possible, because `offset`
986 /// allows the compiler to optimize better. If you need to cross object
987 /// boundaries, cast the pointer to an integer and do the arithmetic there.
994 /// // Iterate using a raw pointer in increments of two elements
995 /// let data = [1u8, 2, 3, 4, 5];
996 /// let mut ptr: *const u8 = data.as_ptr();
998 /// let end_rounded_up = ptr.wrapping_offset(6);
1000 /// // This loop prints "1, 3, 5, "
1001 /// while ptr != end_rounded_up {
1003 /// print!("{}, ", *ptr);
1005 /// ptr = ptr.wrapping_offset(step);
1008 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1010 pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
1012 intrinsics::arith_offset(self, count)
1016 /// Calculates the distance between two pointers. The returned value is in
1017 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1019 /// This function is the inverse of [`offset`].
1021 /// [`offset`]: #method.offset
1022 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
1026 /// If any of the following conditions are violated, the result is Undefined
1029 /// * Both the starting and other pointer must be either in bounds or one
1030 /// byte past the end of the same allocated object.
1032 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1034 /// * The distance between the pointers, in bytes, must be an exact multiple
1035 /// of the size of `T`.
1037 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1039 /// The compiler and standard library generally try to ensure allocations
1040 /// never reach a size where an offset is a concern. For instance, `Vec`
1041 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1042 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1044 /// Most platforms fundamentally can't even construct such an allocation.
1045 /// For instance, no known 64-bit platform can ever serve a request
1046 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1047 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1048 /// more than `isize::MAX` bytes with things like Physical Address
1049 /// Extension. As such, memory acquired directly from allocators or memory
1050 /// mapped files *may* be too large to handle with this function.
1052 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1053 /// difficult to satisfy. The only advantage of this method is that it
1054 /// enables more aggressive compiler optimizations.
1058 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1065 /// #![feature(ptr_offset_from)]
1068 /// let ptr1: *const i32 = &a[1];
1069 /// let ptr2: *const i32 = &a[3];
1071 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1072 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1073 /// assert_eq!(ptr1.offset(2), ptr2);
1074 /// assert_eq!(ptr2.offset(-2), ptr1);
1077 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1079 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1080 let pointee_size = mem::size_of::<T>();
1081 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1083 // This is the same sequence that Clang emits for pointer subtraction.
1084 // It can be neither `nsw` nor `nuw` because the input is treated as
1085 // unsigned but then the output is treated as signed, so neither works.
1086 let d = isize::wrapping_sub(self as _, origin as _);
1087 intrinsics::exact_div(d, pointee_size as _)
1090 /// Calculates the distance between two pointers. The returned value is in
1091 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1093 /// If the address different between the two pointers is not a multiple of
1094 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1097 /// Though this method is safe for any two pointers, note that its result
1098 /// will be mostly useless if the two pointers aren't into the same allocated
1099 /// object, for example if they point to two different local variables.
1103 /// This function panics if `T` is a zero-sized type.
1110 /// #![feature(ptr_wrapping_offset_from)]
1113 /// let ptr1: *const i32 = &a[1];
1114 /// let ptr2: *const i32 = &a[3];
1115 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1116 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1117 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1118 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1120 /// let ptr1: *const i32 = 3 as _;
1121 /// let ptr2: *const i32 = 13 as _;
1122 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1124 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1126 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1127 let pointee_size = mem::size_of::<T>();
1128 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
1130 let d = isize::wrapping_sub(self as _, origin as _);
1131 d.wrapping_div(pointee_size as _)
1134 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1136 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1137 /// offset of `3 * size_of::<T>()` bytes.
1141 /// If any of the following conditions are violated, the result is Undefined
1144 /// * Both the starting and resulting pointer must be either in bounds or one
1145 /// byte past the end of an allocated object.
1147 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1149 /// * The offset being in bounds cannot rely on "wrapping around" the address
1150 /// space. That is, the infinite-precision sum must fit in a `usize`.
1152 /// The compiler and standard library generally tries to ensure allocations
1153 /// never reach a size where an offset is a concern. For instance, `Vec`
1154 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1155 /// `vec.as_ptr().add(vec.len())` is always safe.
1157 /// Most platforms fundamentally can't even construct such an allocation.
1158 /// For instance, no known 64-bit platform can ever serve a request
1159 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1160 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1161 /// more than `isize::MAX` bytes with things like Physical Address
1162 /// Extension. As such, memory acquired directly from allocators or memory
1163 /// mapped files *may* be too large to handle with this function.
1165 /// Consider using `wrapping_offset` instead if these constraints are
1166 /// difficult to satisfy. The only advantage of this method is that it
1167 /// enables more aggressive compiler optimizations.
1174 /// let s: &str = "123";
1175 /// let ptr: *const u8 = s.as_ptr();
1178 /// println!("{}", *ptr.add(1) as char);
1179 /// println!("{}", *ptr.add(2) as char);
1182 #[stable(feature = "pointer_methods", since = "1.26.0")]
1184 pub unsafe fn add(self, count: usize) -> Self
1187 self.offset(count as isize)
1190 /// Calculates the offset from a pointer (convenience for
1191 /// `.offset((count as isize).wrapping_neg())`).
1193 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1194 /// offset of `3 * size_of::<T>()` bytes.
1198 /// If any of the following conditions are violated, the result is Undefined
1201 /// * Both the starting and resulting pointer must be either in bounds or one
1202 /// byte past the end of an allocated object.
1204 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1206 /// * The offset being in bounds cannot rely on "wrapping around" the address
1207 /// space. That is, the infinite-precision sum must fit in a usize.
1209 /// The compiler and standard library generally tries to ensure allocations
1210 /// never reach a size where an offset is a concern. For instance, `Vec`
1211 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1212 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1214 /// Most platforms fundamentally can't even construct such an allocation.
1215 /// For instance, no known 64-bit platform can ever serve a request
1216 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1217 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1218 /// more than `isize::MAX` bytes with things like Physical Address
1219 /// Extension. As such, memory acquired directly from allocators or memory
1220 /// mapped files *may* be too large to handle with this function.
1222 /// Consider using `wrapping_offset` instead if these constraints are
1223 /// difficult to satisfy. The only advantage of this method is that it
1224 /// enables more aggressive compiler optimizations.
1231 /// let s: &str = "123";
1234 /// let end: *const u8 = s.as_ptr().add(3);
1235 /// println!("{}", *end.sub(1) as char);
1236 /// println!("{}", *end.sub(2) as char);
1239 #[stable(feature = "pointer_methods", since = "1.26.0")]
1241 pub unsafe fn sub(self, count: usize) -> Self
1244 self.offset((count as isize).wrapping_neg())
1247 /// Calculates the offset from a pointer using wrapping arithmetic.
1248 /// (convenience for `.wrapping_offset(count as isize)`)
1250 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1251 /// offset of `3 * size_of::<T>()` bytes.
1255 /// The resulting pointer does not need to be in bounds, but it is
1256 /// potentially hazardous to dereference (which requires `unsafe`).
1258 /// Always use `.add(count)` instead when possible, because `add`
1259 /// allows the compiler to optimize better.
1266 /// // Iterate using a raw pointer in increments of two elements
1267 /// let data = [1u8, 2, 3, 4, 5];
1268 /// let mut ptr: *const u8 = data.as_ptr();
1270 /// let end_rounded_up = ptr.wrapping_add(6);
1272 /// // This loop prints "1, 3, 5, "
1273 /// while ptr != end_rounded_up {
1275 /// print!("{}, ", *ptr);
1277 /// ptr = ptr.wrapping_add(step);
1280 #[stable(feature = "pointer_methods", since = "1.26.0")]
1282 pub fn wrapping_add(self, count: usize) -> Self
1285 self.wrapping_offset(count as isize)
1288 /// Calculates the offset from a pointer using wrapping arithmetic.
1289 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
1291 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1292 /// offset of `3 * size_of::<T>()` bytes.
1296 /// The resulting pointer does not need to be in bounds, but it is
1297 /// potentially hazardous to dereference (which requires `unsafe`).
1299 /// Always use `.sub(count)` instead when possible, because `sub`
1300 /// allows the compiler to optimize better.
1307 /// // Iterate using a raw pointer in increments of two elements (backwards)
1308 /// let data = [1u8, 2, 3, 4, 5];
1309 /// let mut ptr: *const u8 = data.as_ptr();
1310 /// let start_rounded_down = ptr.wrapping_sub(2);
1311 /// ptr = ptr.wrapping_add(4);
1313 /// // This loop prints "5, 3, 1, "
1314 /// while ptr != start_rounded_down {
1316 /// print!("{}, ", *ptr);
1318 /// ptr = ptr.wrapping_sub(step);
1321 #[stable(feature = "pointer_methods", since = "1.26.0")]
1323 pub fn wrapping_sub(self, count: usize) -> Self
1326 self.wrapping_offset((count as isize).wrapping_neg())
1329 /// Reads the value from `self` without moving it. This leaves the
1330 /// memory in `self` unchanged.
1334 /// Beyond accepting a raw pointer, this is unsafe because it semantically
1335 /// moves the value out of `self` without preventing further usage of `self`.
1336 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1337 /// `self` is not used before the data is overwritten again (e.g. with `write`,
1338 /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1339 /// because it will attempt to drop the value previously at `*self`.
1341 /// The pointer must be aligned; use `read_unaligned` if that is not the case.
1349 /// let y = &x as *const i32;
1352 /// assert_eq!(y.read(), 12);
1355 #[stable(feature = "pointer_methods", since = "1.26.0")]
1357 pub unsafe fn read(self) -> T
1363 /// Performs a volatile read of the value from `self` without moving it. This
1364 /// leaves the memory in `self` unchanged.
1366 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1367 /// to not be elided or reordered by the compiler across other volatile
1372 /// Rust does not currently have a rigorously and formally defined memory model,
1373 /// so the precise semantics of what "volatile" means here is subject to change
1374 /// over time. That being said, the semantics will almost always end up pretty
1375 /// similar to [C11's definition of volatile][c11].
1377 /// The compiler shouldn't change the relative order or number of volatile
1378 /// memory operations. However, volatile memory operations on zero-sized types
1379 /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
1380 /// and may be ignored.
1382 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1386 /// Beyond accepting a raw pointer, this is unsafe because it semantically
1387 /// moves the value out of `self` without preventing further usage of `self`.
1388 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1389 /// `self` is not used before the data is overwritten again (e.g. with `write`,
1390 /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1391 /// because it will attempt to drop the value previously at `*self`.
1393 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1394 /// on questions involving concurrent access from multiple threads. Volatile
1395 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1396 /// a race between a `read_volatile` and any write operation to the same location
1397 /// is undefined behavior.
1405 /// let y = &x as *const i32;
1408 /// assert_eq!(y.read_volatile(), 12);
1411 #[stable(feature = "pointer_methods", since = "1.26.0")]
1413 pub unsafe fn read_volatile(self) -> T
1419 /// Reads the value from `self` without moving it. This leaves the
1420 /// memory in `self` unchanged.
1422 /// Unlike `read`, the pointer may be unaligned.
1426 /// Beyond accepting a raw pointer, this is unsafe because it semantically
1427 /// moves the value out of `self` without preventing further usage of `self`.
1428 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1429 /// `self` is not used before the data is overwritten again (e.g. with `write`,
1430 /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
1431 /// because it will attempt to drop the value previously at `*self`.
1439 /// let y = &x as *const i32;
1442 /// assert_eq!(y.read_unaligned(), 12);
1445 #[stable(feature = "pointer_methods", since = "1.26.0")]
1447 pub unsafe fn read_unaligned(self) -> T
1450 read_unaligned(self)
1453 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1454 /// and destination may overlap.
1456 /// NOTE: this has the *same* argument order as `ptr::copy`.
1458 /// This is semantically equivalent to C's `memmove`.
1462 /// Care must be taken with the ownership of `self` and `dest`.
1463 /// This method semantically moves the values of `self` into `dest`.
1464 /// However it does not drop the contents of `dest`, or prevent the contents
1465 /// of `self` from being dropped or used.
1469 /// Efficiently create a Rust vector from an unsafe buffer:
1472 /// # #[allow(dead_code)]
1473 /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1474 /// let mut dst = Vec::with_capacity(elts);
1475 /// dst.set_len(elts);
1476 /// ptr.copy_to(dst.as_mut_ptr(), elts);
1480 #[stable(feature = "pointer_methods", since = "1.26.0")]
1482 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
1485 copy(self, dest, count)
1488 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1489 /// and destination may *not* overlap.
1491 /// NOTE: this has the *same* argument order as `ptr::copy_nonoverlapping`.
1493 /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
1497 /// Beyond requiring that the program must be allowed to access both regions
1498 /// of memory, it is Undefined Behavior for source and destination to
1499 /// overlap. Care must also be taken with the ownership of `self` and
1500 /// `self`. This method semantically moves the values of `self` into `dest`.
1501 /// However it does not drop the contents of `dest`, or prevent the contents
1502 /// of `self` from being dropped or used.
1506 /// Efficiently create a Rust vector from an unsafe buffer:
1509 /// # #[allow(dead_code)]
1510 /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
1511 /// let mut dst = Vec::with_capacity(elts);
1512 /// dst.set_len(elts);
1513 /// ptr.copy_to_nonoverlapping(dst.as_mut_ptr(), elts);
1517 #[stable(feature = "pointer_methods", since = "1.26.0")]
1519 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1522 copy_nonoverlapping(self, dest, count)
1525 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1528 /// If it is not possible to align the pointer, the implementation returns
1529 /// `usize::max_value()`.
1531 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1532 /// used with the `offset` or `offset_to` methods.
1534 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
1535 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1536 /// the returned offset is correct in all terms other than alignment.
1540 /// The function panics if `align` is not a power-of-two.
1544 /// Accessing adjacent `u8` as `u16`
1547 /// # #![feature(align_offset)]
1548 /// # fn foo(n: usize) {
1549 /// # use std::mem::align_of;
1551 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1552 /// let ptr = &x[n] as *const u8;
1553 /// let offset = ptr.align_offset(align_of::<u16>());
1554 /// if offset < x.len() - n - 1 {
1555 /// let u16_ptr = ptr.add(offset) as *const u16;
1556 /// assert_ne!(*u16_ptr, 500);
1558 /// // while the pointer can be aligned via `offset`, it would point
1559 /// // outside the allocation
1563 #[unstable(feature = "align_offset", issue = "44488")]
1564 pub fn align_offset(self, align: usize) -> usize where T: Sized {
1565 if !align.is_power_of_two() {
1566 panic!("align_offset: align is not a power-of-two");
1569 align_offset(self, align)
1576 impl<T: ?Sized> *mut T {
1577 /// Returns `true` if the pointer is null.
1579 /// Note that unsized types have many possible null pointers, as only the
1580 /// raw data pointer is considered, not their length, vtable, etc.
1581 /// Therefore, two pointers that are null may still not compare equal to
1589 /// let mut s = [1, 2, 3];
1590 /// let ptr: *mut u32 = s.as_mut_ptr();
1591 /// assert!(!ptr.is_null());
1593 #[stable(feature = "rust1", since = "1.0.0")]
1595 pub fn is_null(self) -> bool {
1596 // Compare via a cast to a thin pointer, so fat pointers are only
1597 // considering their "data" part for null-ness.
1598 (self as *mut u8) == null_mut()
1601 /// Returns `None` if the pointer is null, or else returns a reference to
1602 /// the value wrapped in `Some`.
1606 /// While this method and its mutable counterpart are useful for
1607 /// null-safety, it is important to note that this is still an unsafe
1608 /// operation because the returned value could be pointing to invalid
1611 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
1612 /// not necessarily reflect the actual lifetime of the data.
1619 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1622 /// if let Some(val_back) = ptr.as_ref() {
1623 /// println!("We got back the value: {}!", val_back);
1628 /// # Null-unchecked version
1630 /// If you are sure the pointer can never be null and are looking for some kind of
1631 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>, know that you can
1632 /// dereference the pointer directly.
1635 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1638 /// let val_back = &*ptr;
1639 /// println!("We got back the value: {}!", val_back);
1642 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1644 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
1652 /// Calculates the offset from a pointer.
1654 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1655 /// offset of `3 * size_of::<T>()` bytes.
1659 /// If any of the following conditions are violated, the result is Undefined
1662 /// * Both the starting and resulting pointer must be either in bounds or one
1663 /// byte past the end of *the same* allocated object.
1665 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1667 /// * The offset being in bounds cannot rely on "wrapping around" the address
1668 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
1670 /// The compiler and standard library generally tries to ensure allocations
1671 /// never reach a size where an offset is a concern. For instance, `Vec`
1672 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1673 /// `vec.as_ptr().add(vec.len())` is always safe.
1675 /// Most platforms fundamentally can't even construct such an allocation.
1676 /// For instance, no known 64-bit platform can ever serve a request
1677 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1678 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1679 /// more than `isize::MAX` bytes with things like Physical Address
1680 /// Extension. As such, memory acquired directly from allocators or memory
1681 /// mapped files *may* be too large to handle with this function.
1683 /// Consider using `wrapping_offset` instead if these constraints are
1684 /// difficult to satisfy. The only advantage of this method is that it
1685 /// enables more aggressive compiler optimizations.
1692 /// let mut s = [1, 2, 3];
1693 /// let ptr: *mut u32 = s.as_mut_ptr();
1696 /// println!("{}", *ptr.offset(1));
1697 /// println!("{}", *ptr.offset(2));
1700 #[stable(feature = "rust1", since = "1.0.0")]
1702 pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
1703 intrinsics::offset(self, count) as *mut T
1706 /// Calculates the offset from a pointer using wrapping arithmetic.
1707 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1708 /// offset of `3 * size_of::<T>()` bytes.
1712 /// The resulting pointer does not need to be in bounds, but it is
1713 /// potentially hazardous to dereference (which requires `unsafe`).
1714 /// In particular, the resulting pointer may *not* be used to access a
1715 /// different allocated object than the one `self` points to. In other
1716 /// words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
1717 /// *not* the same as `y`, and dereferencing it is undefined behavior
1718 /// unless `x` and `y` point into the same allocated object.
1720 /// Always use `.offset(count)` instead when possible, because `offset`
1721 /// allows the compiler to optimize better. If you need to cross object
1722 /// boundaries, cast the pointer to an integer and do the arithmetic there.
1729 /// // Iterate using a raw pointer in increments of two elements
1730 /// let mut data = [1u8, 2, 3, 4, 5];
1731 /// let mut ptr: *mut u8 = data.as_mut_ptr();
1733 /// let end_rounded_up = ptr.wrapping_offset(6);
1735 /// while ptr != end_rounded_up {
1739 /// ptr = ptr.wrapping_offset(step);
1741 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
1743 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
1745 pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
1747 intrinsics::arith_offset(self, count) as *mut T
1751 /// Returns `None` if the pointer is null, or else returns a mutable
1752 /// reference to the value wrapped in `Some`.
1756 /// As with `as_ref`, this is unsafe because it cannot verify the validity
1757 /// of the returned pointer, nor can it ensure that the lifetime `'a`
1758 /// returned is indeed a valid lifetime for the contained data.
1765 /// let mut s = [1, 2, 3];
1766 /// let ptr: *mut u32 = s.as_mut_ptr();
1767 /// let first_value = unsafe { ptr.as_mut().unwrap() };
1768 /// *first_value = 4;
1769 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
1771 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
1773 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
1781 /// Calculates the distance between two pointers. The returned value is in
1782 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1784 /// This function is the inverse of [`offset`].
1786 /// [`offset`]: #method.offset-1
1787 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
1791 /// If any of the following conditions are violated, the result is Undefined
1794 /// * Both the starting and other pointer must be either in bounds or one
1795 /// byte past the end of the same allocated object.
1797 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
1799 /// * The distance between the pointers, in bytes, must be an exact multiple
1800 /// of the size of `T`.
1802 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
1804 /// The compiler and standard library generally try to ensure allocations
1805 /// never reach a size where an offset is a concern. For instance, `Vec`
1806 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1807 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
1809 /// Most platforms fundamentally can't even construct such an allocation.
1810 /// For instance, no known 64-bit platform can ever serve a request
1811 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1812 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1813 /// more than `isize::MAX` bytes with things like Physical Address
1814 /// Extension. As such, memory acquired directly from allocators or memory
1815 /// mapped files *may* be too large to handle with this function.
1817 /// Consider using [`wrapping_offset_from`] instead if these constraints are
1818 /// difficult to satisfy. The only advantage of this method is that it
1819 /// enables more aggressive compiler optimizations.
1823 /// This function panics if `T` is a Zero-Sized Type ("ZST").
1830 /// #![feature(ptr_offset_from)]
1832 /// let mut a = [0; 5];
1833 /// let ptr1: *mut i32 = &mut a[1];
1834 /// let ptr2: *mut i32 = &mut a[3];
1836 /// assert_eq!(ptr2.offset_from(ptr1), 2);
1837 /// assert_eq!(ptr1.offset_from(ptr2), -2);
1838 /// assert_eq!(ptr1.offset(2), ptr2);
1839 /// assert_eq!(ptr2.offset(-2), ptr1);
1842 #[unstable(feature = "ptr_offset_from", issue = "41079")]
1844 pub unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized {
1845 (self as *const T).offset_from(origin)
1848 /// Calculates the distance between two pointers. The returned value is in
1849 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
1851 /// If the address different between the two pointers is not a multiple of
1852 /// `mem::size_of::<T>()` then the result of the division is rounded towards
1855 /// Though this method is safe for any two pointers, note that its result
1856 /// will be mostly useless if the two pointers aren't into the same allocated
1857 /// object, for example if they point to two different local variables.
1861 /// This function panics if `T` is a zero-sized type.
1868 /// #![feature(ptr_wrapping_offset_from)]
1870 /// let mut a = [0; 5];
1871 /// let ptr1: *mut i32 = &mut a[1];
1872 /// let ptr2: *mut i32 = &mut a[3];
1873 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1874 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
1875 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
1876 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
1878 /// let ptr1: *mut i32 = 3 as _;
1879 /// let ptr2: *mut i32 = 13 as _;
1880 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
1882 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
1884 pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized {
1885 (self as *const T).wrapping_offset_from(origin)
1888 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
1890 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1891 /// offset of `3 * size_of::<T>()` bytes.
1895 /// If any of the following conditions are violated, the result is Undefined
1898 /// * Both the starting and resulting pointer must be either in bounds or one
1899 /// byte past the end of an allocated object.
1901 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1903 /// * The offset being in bounds cannot rely on "wrapping around" the address
1904 /// space. That is, the infinite-precision sum must fit in a `usize`.
1906 /// The compiler and standard library generally tries to ensure allocations
1907 /// never reach a size where an offset is a concern. For instance, `Vec`
1908 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1909 /// `vec.as_ptr().add(vec.len())` is always safe.
1911 /// Most platforms fundamentally can't even construct such an allocation.
1912 /// For instance, no known 64-bit platform can ever serve a request
1913 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1914 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1915 /// more than `isize::MAX` bytes with things like Physical Address
1916 /// Extension. As such, memory acquired directly from allocators or memory
1917 /// mapped files *may* be too large to handle with this function.
1919 /// Consider using `wrapping_offset` instead if these constraints are
1920 /// difficult to satisfy. The only advantage of this method is that it
1921 /// enables more aggressive compiler optimizations.
1928 /// let s: &str = "123";
1929 /// let ptr: *const u8 = s.as_ptr();
1932 /// println!("{}", *ptr.add(1) as char);
1933 /// println!("{}", *ptr.add(2) as char);
1936 #[stable(feature = "pointer_methods", since = "1.26.0")]
1938 pub unsafe fn add(self, count: usize) -> Self
1941 self.offset(count as isize)
1944 /// Calculates the offset from a pointer (convenience for
1945 /// `.offset((count as isize).wrapping_neg())`).
1947 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
1948 /// offset of `3 * size_of::<T>()` bytes.
1952 /// If any of the following conditions are violated, the result is Undefined
1955 /// * Both the starting and resulting pointer must be either in bounds or one
1956 /// byte past the end of an allocated object.
1958 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1960 /// * The offset being in bounds cannot rely on "wrapping around" the address
1961 /// space. That is, the infinite-precision sum must fit in a usize.
1963 /// The compiler and standard library generally tries to ensure allocations
1964 /// never reach a size where an offset is a concern. For instance, `Vec`
1965 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1966 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1968 /// Most platforms fundamentally can't even construct such an allocation.
1969 /// For instance, no known 64-bit platform can ever serve a request
1970 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1971 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1972 /// more than `isize::MAX` bytes with things like Physical Address
1973 /// Extension. As such, memory acquired directly from allocators or memory
1974 /// mapped files *may* be too large to handle with this function.
1976 /// Consider using `wrapping_offset` instead if these constraints are
1977 /// difficult to satisfy. The only advantage of this method is that it
1978 /// enables more aggressive compiler optimizations.
1985 /// let s: &str = "123";
1988 /// let end: *const u8 = s.as_ptr().add(3);
1989 /// println!("{}", *end.sub(1) as char);
1990 /// println!("{}", *end.sub(2) as char);
1993 #[stable(feature = "pointer_methods", since = "1.26.0")]
1995 pub unsafe fn sub(self, count: usize) -> Self
1998 self.offset((count as isize).wrapping_neg())
2001 /// Calculates the offset from a pointer using wrapping arithmetic.
2002 /// (convenience for `.wrapping_offset(count as isize)`)
2004 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
2005 /// offset of `3 * size_of::<T>()` bytes.
2009 /// The resulting pointer does not need to be in bounds, but it is
2010 /// potentially hazardous to dereference (which requires `unsafe`).
2012 /// Always use `.add(count)` instead when possible, because `add`
2013 /// allows the compiler to optimize better.
2020 /// // Iterate using a raw pointer in increments of two elements
2021 /// let data = [1u8, 2, 3, 4, 5];
2022 /// let mut ptr: *const u8 = data.as_ptr();
2024 /// let end_rounded_up = ptr.wrapping_add(6);
2026 /// // This loop prints "1, 3, 5, "
2027 /// while ptr != end_rounded_up {
2029 /// print!("{}, ", *ptr);
2031 /// ptr = ptr.wrapping_add(step);
2034 #[stable(feature = "pointer_methods", since = "1.26.0")]
2036 pub fn wrapping_add(self, count: usize) -> Self
2039 self.wrapping_offset(count as isize)
2042 /// Calculates the offset from a pointer using wrapping arithmetic.
2043 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
2045 /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
2046 /// offset of `3 * size_of::<T>()` bytes.
2050 /// The resulting pointer does not need to be in bounds, but it is
2051 /// potentially hazardous to dereference (which requires `unsafe`).
2053 /// Always use `.sub(count)` instead when possible, because `sub`
2054 /// allows the compiler to optimize better.
2061 /// // Iterate using a raw pointer in increments of two elements (backwards)
2062 /// let data = [1u8, 2, 3, 4, 5];
2063 /// let mut ptr: *const u8 = data.as_ptr();
2064 /// let start_rounded_down = ptr.wrapping_sub(2);
2065 /// ptr = ptr.wrapping_add(4);
2067 /// // This loop prints "5, 3, 1, "
2068 /// while ptr != start_rounded_down {
2070 /// print!("{}, ", *ptr);
2072 /// ptr = ptr.wrapping_sub(step);
2075 #[stable(feature = "pointer_methods", since = "1.26.0")]
2077 pub fn wrapping_sub(self, count: usize) -> Self
2080 self.wrapping_offset((count as isize).wrapping_neg())
2083 /// Reads the value from `self` without moving it. This leaves the
2084 /// memory in `self` unchanged.
2088 /// Beyond accepting a raw pointer, this is unsafe because it semantically
2089 /// moves the value out of `self` without preventing further usage of `self`.
2090 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
2091 /// `self` is not used before the data is overwritten again (e.g. with `write`,
2092 /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
2093 /// because it will attempt to drop the value previously at `*self`.
2095 /// The pointer must be aligned; use `read_unaligned` if that is not the case.
2103 /// let y = &x as *const i32;
2106 /// assert_eq!(y.read(), 12);
2109 #[stable(feature = "pointer_methods", since = "1.26.0")]
2111 pub unsafe fn read(self) -> T
2117 /// Performs a volatile read of the value from `self` without moving it. This
2118 /// leaves the memory in `self` unchanged.
2120 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2121 /// to not be elided or reordered by the compiler across other volatile
2126 /// Rust does not currently have a rigorously and formally defined memory model,
2127 /// so the precise semantics of what "volatile" means here is subject to change
2128 /// over time. That being said, the semantics will almost always end up pretty
2129 /// similar to [C11's definition of volatile][c11].
2131 /// The compiler shouldn't change the relative order or number of volatile
2132 /// memory operations. However, volatile memory operations on zero-sized types
2133 /// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
2134 /// and may be ignored.
2136 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
2140 /// Beyond accepting a raw pointer, this is unsafe because it semantically
2141 /// moves the value out of `self` without preventing further usage of `self`.
2142 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
2143 /// `self` is not used before the data is overwritten again (e.g. with `write`,
2144 /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
2145 /// because it will attempt to drop the value previously at `*self`.
2147 /// Just like in C, whether an operation is volatile has no bearing whatsoever
2148 /// on questions involving concurrent access from multiple threads. Volatile
2149 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
2150 /// a race between a `read_volatile` and any write operation to the same location
2151 /// is undefined behavior.
2159 /// let y = &x as *const i32;
2162 /// assert_eq!(y.read_volatile(), 12);
2165 #[stable(feature = "pointer_methods", since = "1.26.0")]
2167 pub unsafe fn read_volatile(self) -> T
2173 /// Reads the value from `self` without moving it. This leaves the
2174 /// memory in `self` unchanged.
2176 /// Unlike `read`, the pointer may be unaligned.
2180 /// Beyond accepting a raw pointer, this is unsafe because it semantically
2181 /// moves the value out of `self` without preventing further usage of `self`.
2182 /// If `T` is not `Copy`, then care must be taken to ensure that the value at
2183 /// `self` is not used before the data is overwritten again (e.g. with `write`,
2184 /// `write_bytes`, or `copy`). Note that `*self = foo` counts as a use
2185 /// because it will attempt to drop the value previously at `*self`.
2193 /// let y = &x as *const i32;
2196 /// assert_eq!(y.read_unaligned(), 12);
2199 #[stable(feature = "pointer_methods", since = "1.26.0")]
2201 pub unsafe fn read_unaligned(self) -> T
2204 read_unaligned(self)
2207 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2208 /// and destination may overlap.
2210 /// NOTE: this has the *same* argument order as `ptr::copy`.
2212 /// This is semantically equivalent to C's `memmove`.
2216 /// Care must be taken with the ownership of `self` and `dest`.
2217 /// This method semantically moves the values of `self` into `dest`.
2218 /// However it does not drop the contents of `self`, or prevent the contents
2219 /// of `dest` from being dropped or used.
2223 /// Efficiently create a Rust vector from an unsafe buffer:
2226 /// # #[allow(dead_code)]
2227 /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
2228 /// let mut dst = Vec::with_capacity(elts);
2229 /// dst.set_len(elts);
2230 /// ptr.copy_to(dst.as_mut_ptr(), elts);
2234 #[stable(feature = "pointer_methods", since = "1.26.0")]
2236 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
2239 copy(self, dest, count)
2242 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
2243 /// and destination may *not* overlap.
2245 /// NOTE: this has the *same* argument order as `ptr::copy_nonoverlapping`.
2247 /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
2251 /// Beyond requiring that the program must be allowed to access both regions
2252 /// of memory, it is Undefined Behavior for source and destination to
2253 /// overlap. Care must also be taken with the ownership of `self` and
2254 /// `self`. This method semantically moves the values of `self` into `dest`.
2255 /// However it does not drop the contents of `dest`, or prevent the contents
2256 /// of `self` from being dropped or used.
2260 /// Efficiently create a Rust vector from an unsafe buffer:
2263 /// # #[allow(dead_code)]
2264 /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
2265 /// let mut dst = Vec::with_capacity(elts);
2266 /// dst.set_len(elts);
2267 /// ptr.copy_to_nonoverlapping(dst.as_mut_ptr(), elts);
2271 #[stable(feature = "pointer_methods", since = "1.26.0")]
2273 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
2276 copy_nonoverlapping(self, dest, count)
2279 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2280 /// and destination may overlap.
2282 /// NOTE: this has the *opposite* argument order of `ptr::copy`.
2284 /// This is semantically equivalent to C's `memmove`.
2288 /// Care must be taken with the ownership of `src` and `self`.
2289 /// This method semantically moves the values of `src` into `self`.
2290 /// However it does not drop the contents of `self`, or prevent the contents
2291 /// of `src` from being dropped or used.
2295 /// Efficiently create a Rust vector from an unsafe buffer:
2298 /// # #[allow(dead_code)]
2299 /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
2300 /// let mut dst: Vec<T> = Vec::with_capacity(elts);
2301 /// dst.set_len(elts);
2302 /// dst.as_mut_ptr().copy_from(ptr, elts);
2306 #[stable(feature = "pointer_methods", since = "1.26.0")]
2308 pub unsafe fn copy_from(self, src: *const T, count: usize)
2311 copy(src, self, count)
2314 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
2315 /// and destination may *not* overlap.
2317 /// NOTE: this has the *opposite* argument order of `ptr::copy_nonoverlapping`.
2319 /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
2323 /// Beyond requiring that the program must be allowed to access both regions
2324 /// of memory, it is Undefined Behavior for source and destination to
2325 /// overlap. Care must also be taken with the ownership of `src` and
2326 /// `self`. This method semantically moves the values of `src` into `self`.
2327 /// However it does not drop the contents of `self`, or prevent the contents
2328 /// of `src` from being dropped or used.
2332 /// Efficiently create a Rust vector from an unsafe buffer:
2335 /// # #[allow(dead_code)]
2336 /// unsafe fn from_buf_raw<T: Copy>(ptr: *const T, elts: usize) -> Vec<T> {
2337 /// let mut dst: Vec<T> = Vec::with_capacity(elts);
2338 /// dst.set_len(elts);
2339 /// dst.as_mut_ptr().copy_from_nonoverlapping(ptr, elts);
2343 #[stable(feature = "pointer_methods", since = "1.26.0")]
2345 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
2348 copy_nonoverlapping(src, self, count)
2351 /// Executes the destructor (if any) of the pointed-to value.
2353 /// This has two use cases:
2355 /// * It is *required* to use `drop_in_place` to drop unsized types like
2356 /// trait objects, because they can't be read out onto the stack and
2357 /// dropped normally.
2359 /// * It is friendlier to the optimizer to do this over `ptr::read` when
2360 /// dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
2361 /// as the compiler doesn't need to prove that it's sound to elide the
2366 /// This has all the same safety problems as `ptr::read` with respect to
2367 /// invalid pointers, types, and double drops.
2368 #[stable(feature = "pointer_methods", since = "1.26.0")]
2370 pub unsafe fn drop_in_place(self) {
2374 /// Overwrites a memory location with the given value without reading or
2375 /// dropping the old value.
2379 /// This operation is marked unsafe because it writes through a raw pointer.
2381 /// It does not drop the contents of `self`. This is safe, but it could leak
2382 /// allocations or resources, so care must be taken not to overwrite an object
2383 /// that should be dropped.
2385 /// Additionally, it does not drop `val`. Semantically, `val` is moved into the
2386 /// location pointed to by `self`.
2388 /// This is appropriate for initializing uninitialized memory, or overwriting
2389 /// memory that has previously been `read` from.
2391 /// The pointer must be aligned; use `write_unaligned` if that is not the case.
2399 /// let y = &mut x as *mut i32;
2404 /// assert_eq!(y.read(), 12);
2407 #[stable(feature = "pointer_methods", since = "1.26.0")]
2409 pub unsafe fn write(self, val: T)
2415 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
2416 /// bytes of memory starting at `self` to `val`.
2421 /// let mut vec = vec![0; 4];
2423 /// let vec_ptr = vec.as_mut_ptr();
2424 /// vec_ptr.write_bytes(b'a', 2);
2426 /// assert_eq!(vec, [b'a', b'a', 0, 0]);
2428 #[stable(feature = "pointer_methods", since = "1.26.0")]
2430 pub unsafe fn write_bytes(self, val: u8, count: usize)
2433 write_bytes(self, val, count)
2436 /// Performs a volatile write of a memory location with the given value without
2437 /// reading or dropping the old value.
2439 /// Volatile operations are intended to act on I/O memory, and are guaranteed
2440 /// to not be elided or reordered by the compiler across other volatile
2445 /// Rust does not currently have a rigorously and formally defined memory model,
2446 /// so the precise semantics of what "volatile" means here is subject to change
2447 /// over time. That being said, the semantics will almost always end up pretty
2448 /// similar to [C11's definition of volatile][c11].
2450 /// The compiler shouldn't change the relative order or number of volatile
2451 /// memory operations. However, volatile memory operations on zero-sized types
2452 /// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops
2453 /// and may be ignored.
2455 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
2459 /// This operation is marked unsafe because it accepts a raw pointer.
2461 /// It does not drop the contents of `self`. This is safe, but it could leak
2462 /// allocations or resources, so care must be taken not to overwrite an object
2463 /// that should be dropped.
2465 /// This is appropriate for initializing uninitialized memory, or overwriting
2466 /// memory that has previously been `read` from.
2468 /// Just like in C, whether an operation is volatile has no bearing whatsoever
2469 /// on questions involving concurrent access from multiple threads. Volatile
2470 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
2471 /// a race between a `write_volatile` and any other operation (reading or writing)
2472 /// on the same location is undefined behavior.
2480 /// let y = &mut x as *mut i32;
2484 /// y.write_volatile(z);
2485 /// assert_eq!(y.read_volatile(), 12);
2488 #[stable(feature = "pointer_methods", since = "1.26.0")]
2490 pub unsafe fn write_volatile(self, val: T)
2493 write_volatile(self, val)
2496 /// Overwrites a memory location with the given value without reading or
2497 /// dropping the old value.
2499 /// Unlike `write`, the pointer may be unaligned.
2503 /// This operation is marked unsafe because it writes through a raw pointer.
2505 /// It does not drop the contents of `self`. This is safe, but it could leak
2506 /// allocations or resources, so care must be taken not to overwrite an object
2507 /// that should be dropped.
2509 /// Additionally, it does not drop `self`. Semantically, `self` is moved into the
2510 /// location pointed to by `val`.
2512 /// This is appropriate for initializing uninitialized memory, or overwriting
2513 /// memory that has previously been `read` from.
2521 /// let y = &mut x as *mut i32;
2525 /// y.write_unaligned(z);
2526 /// assert_eq!(y.read_unaligned(), 12);
2529 #[stable(feature = "pointer_methods", since = "1.26.0")]
2531 pub unsafe fn write_unaligned(self, val: T)
2534 write_unaligned(self, val)
2537 /// Replaces the value at `self` with `src`, returning the old
2538 /// value, without dropping either.
2542 /// This is only unsafe because it accepts a raw pointer.
2543 /// Otherwise, this operation is identical to `mem::replace`.
2544 #[stable(feature = "pointer_methods", since = "1.26.0")]
2546 pub unsafe fn replace(self, src: T) -> T
2552 /// Swaps the values at two mutable locations of the same type, without
2553 /// deinitializing either. They may overlap, unlike `mem::swap` which is
2554 /// otherwise equivalent.
2558 /// This function copies the memory through the raw pointers passed to it
2561 /// Ensure that these pointers are valid before calling `swap`.
2562 #[stable(feature = "pointer_methods", since = "1.26.0")]
2564 pub unsafe fn swap(self, with: *mut T)
2570 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
2573 /// If it is not possible to align the pointer, the implementation returns
2574 /// `usize::max_value()`.
2576 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
2577 /// used with the `offset` or `offset_to` methods.
2579 /// There are no guarantees whatsover that offsetting the pointer will not overflow or go
2580 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
2581 /// the returned offset is correct in all terms other than alignment.
2585 /// The function panics if `align` is not a power-of-two.
2589 /// Accessing adjacent `u8` as `u16`
2592 /// # #![feature(align_offset)]
2593 /// # fn foo(n: usize) {
2594 /// # use std::mem::align_of;
2596 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
2597 /// let ptr = &x[n] as *const u8;
2598 /// let offset = ptr.align_offset(align_of::<u16>());
2599 /// if offset < x.len() - n - 1 {
2600 /// let u16_ptr = ptr.add(offset) as *const u16;
2601 /// assert_ne!(*u16_ptr, 500);
2603 /// // while the pointer can be aligned via `offset`, it would point
2604 /// // outside the allocation
2608 #[unstable(feature = "align_offset", issue = "44488")]
2609 pub fn align_offset(self, align: usize) -> usize where T: Sized {
2610 if !align.is_power_of_two() {
2611 panic!("align_offset: align is not a power-of-two");
2614 align_offset(self, align)
2619 /// Align pointer `p`.
2621 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
2622 /// to pointer `p` so that pointer `p` would get aligned to `a`.
2624 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
2625 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2628 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2629 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2630 /// than trying to adapt this to accommodate that change.
2632 /// Any questions go to @nagisa.
2633 #[lang="align_offset"]
2634 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2635 /// Calculate multiplicative modular inverse of `x` modulo `m`.
2637 /// This implementation is tailored for align_offset and has following preconditions:
2639 /// * `m` is a power-of-two;
2640 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2642 /// Implementation of this function shall not panic. Ever.
2644 fn mod_inv(x: usize, m: usize) -> usize {
2645 /// Multiplicative modular inverse table modulo 2⁴ = 16.
2647 /// Note, that this table does not contain values where inverse does not exist (i.e. for
2648 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2649 const INV_TABLE_MOD_16: [usize; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2650 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2651 const INV_TABLE_MOD: usize = 16;
2653 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
2655 let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1];
2656 if m <= INV_TABLE_MOD {
2657 table_inverse & (m - 1)
2659 // We iterate "up" using the following formula:
2661 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2663 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
2664 let mut inverse = table_inverse;
2665 let mut going_mod = INV_TABLE_MOD_SQUARED;
2667 // y = y * (2 - xy) mod n
2669 // Note, that we use wrapping operations here intentionally – the original formula
2670 // uses e.g. subtraction `mod n`. It is entirely fine to do them `mod
2671 // usize::max_value()` instead, because we take the result `mod n` at the end
2673 inverse = inverse.wrapping_mul(
2674 2usize.wrapping_sub(x.wrapping_mul(inverse))
2675 ) & (going_mod - 1);
2677 return inverse & (m - 1);
2679 going_mod = going_mod.wrapping_mul(going_mod);
2684 let stride = ::mem::size_of::<T>();
2685 let a_minus_one = a.wrapping_sub(1);
2686 let pmoda = p as usize & a_minus_one;
2689 // Already aligned. Yay!
2694 return if stride == 0 {
2695 // If the pointer is not aligned, and the element is zero-sized, then no amount of
2696 // elements will ever align the pointer.
2699 a.wrapping_sub(pmoda)
2703 let smoda = stride & a_minus_one;
2704 // a is power-of-two so cannot be 0. stride = 0 is handled above.
2705 let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a));
2706 let gcd = 1usize << gcdpow;
2709 // This branch solves for the variable $o$ in following linear congruence equation:
2711 // ⎰ p + o ≡ 0 (mod a) # $p + o$ must be aligned to specified alignment $a$
2712 // ⎱ o ≡ 0 (mod s) # offset $o$ must be a multiple of stride $s$
2716 // * a, s are co-prime
2718 // This gives us the formula below:
2720 // o = (a - (p mod a)) * (s⁻¹ mod a) * s
2722 // The first term is “the relative alignment of p to a”, the second term is “how does
2723 // incrementing p by one s change the relative alignment of p”, the third term is
2724 // translating change in units of s to a byte count.
2726 // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
2727 // to take the result $o mod lcm(s, a)$. Since $s$ and $a$ are co-prime (i.e. $gcd(s, a) =
2728 // 1$) and $lcm(s, a) = s * a / gcd(s, a)$, we can replace $lcm(s, a)$ with just a $s * a$.
2730 // (Author note: we decided later on to express the offset in "elements" rather than bytes,
2731 // which drops the multiplication by `s` on both sides of the modulo.)
2732 return intrinsics::unchecked_rem(a.wrapping_sub(pmoda).wrapping_mul(mod_inv(smoda, a)), a);
2735 if p as usize & (gcd - 1) == 0 {
2736 // This can be aligned, but `a` and `stride` are not co-prime, so a somewhat adapted
2738 let j = a.wrapping_sub(pmoda) >> gcdpow;
2739 let k = smoda >> gcdpow;
2740 return intrinsics::unchecked_rem(j.wrapping_mul(mod_inv(k, a)), a >> gcdpow);
2743 // Cannot be aligned at all.
2749 // Equality for pointers
2750 #[stable(feature = "rust1", since = "1.0.0")]
2751 impl<T: ?Sized> PartialEq for *const T {
2753 fn eq(&self, other: &*const T) -> bool { *self == *other }
2756 #[stable(feature = "rust1", since = "1.0.0")]
2757 impl<T: ?Sized> Eq for *const T {}
2759 #[stable(feature = "rust1", since = "1.0.0")]
2760 impl<T: ?Sized> PartialEq for *mut T {
2762 fn eq(&self, other: &*mut T) -> bool { *self == *other }
2765 #[stable(feature = "rust1", since = "1.0.0")]
2766 impl<T: ?Sized> Eq for *mut T {}
2768 /// Compare raw pointers for equality.
2770 /// This is the same as using the `==` operator, but less generic:
2771 /// the arguments have to be `*const T` raw pointers,
2772 /// not anything that implements `PartialEq`.
2774 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2775 /// by their address rather than comparing the values they point to
2776 /// (which is what the `PartialEq for &T` implementation does).
2784 /// let other_five = 5;
2785 /// let five_ref = &five;
2786 /// let same_five_ref = &five;
2787 /// let other_five_ref = &other_five;
2789 /// assert!(five_ref == same_five_ref);
2790 /// assert!(five_ref == other_five_ref);
2792 /// assert!(ptr::eq(five_ref, same_five_ref));
2793 /// assert!(!ptr::eq(five_ref, other_five_ref));
2795 #[stable(feature = "ptr_eq", since = "1.17.0")]
2797 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
2801 // Impls for function pointers
2802 macro_rules! fnptr_impls_safety_abi {
2803 ($FnTy: ty, $($Arg: ident),*) => {
2804 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2805 impl<Ret, $($Arg),*> PartialEq for $FnTy {
2807 fn eq(&self, other: &Self) -> bool {
2808 *self as usize == *other as usize
2812 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2813 impl<Ret, $($Arg),*> Eq for $FnTy {}
2815 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2816 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
2818 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2819 (*self as usize).partial_cmp(&(*other as usize))
2823 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2824 impl<Ret, $($Arg),*> Ord for $FnTy {
2826 fn cmp(&self, other: &Self) -> Ordering {
2827 (*self as usize).cmp(&(*other as usize))
2831 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2832 impl<Ret, $($Arg),*> hash::Hash for $FnTy {
2833 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2834 state.write_usize(*self as usize)
2838 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2839 impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
2840 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2841 fmt::Pointer::fmt(&(*self as *const ()), f)
2845 #[stable(feature = "fnptr_impls", since = "1.4.0")]
2846 impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
2847 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2848 fmt::Pointer::fmt(&(*self as *const ()), f)
2854 macro_rules! fnptr_impls_args {
2855 ($($Arg: ident),+) => {
2856 fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2857 fnptr_impls_safety_abi! { extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2858 fnptr_impls_safety_abi! { extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2859 fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),*) -> Ret, $($Arg),* }
2860 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),*) -> Ret, $($Arg),* }
2861 fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),* , ...) -> Ret, $($Arg),* }
2864 // No variadic functions with 0 parameters
2865 fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
2866 fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
2867 fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
2868 fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
2872 fnptr_impls_args! { }
2873 fnptr_impls_args! { A }
2874 fnptr_impls_args! { A, B }
2875 fnptr_impls_args! { A, B, C }
2876 fnptr_impls_args! { A, B, C, D }
2877 fnptr_impls_args! { A, B, C, D, E }
2878 fnptr_impls_args! { A, B, C, D, E, F }
2879 fnptr_impls_args! { A, B, C, D, E, F, G }
2880 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2881 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2882 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2883 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2884 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2886 // Comparison for pointers
2887 #[stable(feature = "rust1", since = "1.0.0")]
2888 impl<T: ?Sized> Ord for *const T {
2890 fn cmp(&self, other: &*const T) -> Ordering {
2893 } else if self == other {
2901 #[stable(feature = "rust1", since = "1.0.0")]
2902 impl<T: ?Sized> PartialOrd for *const T {
2904 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
2905 Some(self.cmp(other))
2909 fn lt(&self, other: &*const T) -> bool { *self < *other }
2912 fn le(&self, other: &*const T) -> bool { *self <= *other }
2915 fn gt(&self, other: &*const T) -> bool { *self > *other }
2918 fn ge(&self, other: &*const T) -> bool { *self >= *other }
2921 #[stable(feature = "rust1", since = "1.0.0")]
2922 impl<T: ?Sized> Ord for *mut T {
2924 fn cmp(&self, other: &*mut T) -> Ordering {
2927 } else if self == other {
2935 #[stable(feature = "rust1", since = "1.0.0")]
2936 impl<T: ?Sized> PartialOrd for *mut T {
2938 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2939 Some(self.cmp(other))
2943 fn lt(&self, other: &*mut T) -> bool { *self < *other }
2946 fn le(&self, other: &*mut T) -> bool { *self <= *other }
2949 fn gt(&self, other: &*mut T) -> bool { *self > *other }
2952 fn ge(&self, other: &*mut T) -> bool { *self >= *other }
2955 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
2956 /// of this wrapper owns the referent. Useful for building abstractions like
2957 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
2959 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
2960 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
2961 /// the kind of strong aliasing guarantees an instance of `T` can expect:
2962 /// the referent of the pointer should not be modified without a unique path to
2963 /// its owning Unique.
2965 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
2966 /// consider using `NonNull`, which has weaker semantics.
2968 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
2969 /// is never dereferenced. This is so that enums may use this forbidden value
2970 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
2971 /// However the pointer may still dangle if it isn't dereferenced.
2973 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
2974 /// for any type which upholds Unique's aliasing requirements.
2975 #[unstable(feature = "ptr_internals", issue = "0",
2976 reason = "use NonNull instead and consider PhantomData<T> \
2977 (if you also use #[may_dangle]), Send, and/or Sync")]
2979 #[repr(transparent)]
2980 pub struct Unique<T: ?Sized> {
2981 pointer: NonZero<*const T>,
2982 // NOTE: this marker has no consequences for variance, but is necessary
2983 // for dropck to understand that we logically own a `T`.
2985 // For details, see:
2986 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
2987 _marker: PhantomData<T>,
2990 #[unstable(feature = "ptr_internals", issue = "0")]
2991 impl<T: ?Sized> fmt::Debug for Unique<T> {
2992 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2993 fmt::Pointer::fmt(&self.as_ptr(), f)
2997 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
2998 /// reference is unaliased. Note that this aliasing invariant is
2999 /// unenforced by the type system; the abstraction using the
3000 /// `Unique` must enforce it.
3001 #[unstable(feature = "ptr_internals", issue = "0")]
3002 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
3004 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
3005 /// reference is unaliased. Note that this aliasing invariant is
3006 /// unenforced by the type system; the abstraction using the
3007 /// `Unique` must enforce it.
3008 #[unstable(feature = "ptr_internals", issue = "0")]
3009 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
3011 #[unstable(feature = "ptr_internals", issue = "0")]
3012 impl<T: Sized> Unique<T> {
3013 /// Creates a new `Unique` that is dangling, but well-aligned.
3015 /// This is useful for initializing types which lazily allocate, like
3016 /// `Vec::new` does.
3018 /// Note that the pointer value may potentially represent a valid pointer to
3019 /// a `T`, which means this must not be used as a "not yet initialized"
3020 /// sentinel value. Types that lazily allocate must track initialization by
3021 /// some other means.
3022 // FIXME: rename to dangling() to match NonNull?
3023 pub const fn empty() -> Self {
3025 Unique::new_unchecked(mem::align_of::<T>() as *mut T)
3030 #[unstable(feature = "ptr_internals", issue = "0")]
3031 impl<T: ?Sized> Unique<T> {
3032 /// Creates a new `Unique`.
3036 /// `ptr` must be non-null.
3037 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
3038 Unique { pointer: NonZero(ptr as _), _marker: PhantomData }
3041 /// Creates a new `Unique` if `ptr` is non-null.
3042 pub fn new(ptr: *mut T) -> Option<Self> {
3044 Some(Unique { pointer: NonZero(ptr as _), _marker: PhantomData })
3050 /// Acquires the underlying `*mut` pointer.
3051 pub fn as_ptr(self) -> *mut T {
3052 self.pointer.0 as *mut T
3055 /// Dereferences the content.
3057 /// The resulting lifetime is bound to self so this behaves "as if"
3058 /// it were actually an instance of T that is getting borrowed. If a longer
3059 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
3060 pub unsafe fn as_ref(&self) -> &T {
3064 /// Mutably dereferences the content.
3066 /// The resulting lifetime is bound to self so this behaves "as if"
3067 /// it were actually an instance of T that is getting borrowed. If a longer
3068 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
3069 pub unsafe fn as_mut(&mut self) -> &mut T {
3074 #[unstable(feature = "ptr_internals", issue = "0")]
3075 impl<T: ?Sized> Clone for Unique<T> {
3076 fn clone(&self) -> Self {
3081 #[unstable(feature = "ptr_internals", issue = "0")]
3082 impl<T: ?Sized> Copy for Unique<T> { }
3084 #[unstable(feature = "ptr_internals", issue = "0")]
3085 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
3087 #[unstable(feature = "ptr_internals", issue = "0")]
3088 impl<T: ?Sized> fmt::Pointer for Unique<T> {
3089 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3090 fmt::Pointer::fmt(&self.as_ptr(), f)
3094 #[unstable(feature = "ptr_internals", issue = "0")]
3095 impl<'a, T: ?Sized> From<&'a mut T> for Unique<T> {
3096 fn from(reference: &'a mut T) -> Self {
3097 Unique { pointer: NonZero(reference as _), _marker: PhantomData }
3101 #[unstable(feature = "ptr_internals", issue = "0")]
3102 impl<'a, T: ?Sized> From<&'a T> for Unique<T> {
3103 fn from(reference: &'a T) -> Self {
3104 Unique { pointer: NonZero(reference as _), _marker: PhantomData }
3108 #[unstable(feature = "ptr_internals", issue = "0")]
3109 impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
3110 fn from(p: NonNull<T>) -> Self {
3111 Unique { pointer: p.pointer, _marker: PhantomData }
3115 /// `*mut T` but non-zero and covariant.
3117 /// This is often the correct thing to use when building data structures using
3118 /// raw pointers, but is ultimately more dangerous to use because of its additional
3119 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
3121 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
3122 /// is never dereferenced. This is so that enums may use this forbidden value
3123 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
3124 /// However the pointer may still dangle if it isn't dereferenced.
3126 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
3127 /// for your use case, you should include some PhantomData in your type to
3128 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
3129 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
3130 /// such as Box, Rc, Arc, Vec, and LinkedList. This is the case because they
3131 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
3132 #[stable(feature = "nonnull", since = "1.25.0")]
3133 #[repr(transparent)]
3134 pub struct NonNull<T: ?Sized> {
3135 pointer: NonZero<*const T>,
3138 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
3139 // NB: This impl is unnecessary, but should provide better error messages.
3140 #[stable(feature = "nonnull", since = "1.25.0")]
3141 impl<T: ?Sized> !Send for NonNull<T> { }
3143 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
3144 // NB: This impl is unnecessary, but should provide better error messages.
3145 #[stable(feature = "nonnull", since = "1.25.0")]
3146 impl<T: ?Sized> !Sync for NonNull<T> { }
3148 impl<T: Sized> NonNull<T> {
3149 /// Creates a new `NonNull` that is dangling, but well-aligned.
3151 /// This is useful for initializing types which lazily allocate, like
3152 /// `Vec::new` does.
3154 /// Note that the pointer value may potentially represent a valid pointer to
3155 /// a `T`, which means this must not be used as a "not yet initialized"
3156 /// sentinel value. Types that lazily allocate must track initialization by
3157 /// some other means.
3158 #[stable(feature = "nonnull", since = "1.25.0")]
3159 pub fn dangling() -> Self {
3161 let ptr = mem::align_of::<T>() as *mut T;
3162 NonNull::new_unchecked(ptr)
3167 impl<T: ?Sized> NonNull<T> {
3168 /// Creates a new `NonNull`.
3172 /// `ptr` must be non-null.
3173 #[stable(feature = "nonnull", since = "1.25.0")]
3174 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
3175 NonNull { pointer: NonZero(ptr as _) }
3178 /// Creates a new `NonNull` if `ptr` is non-null.
3179 #[stable(feature = "nonnull", since = "1.25.0")]
3180 pub fn new(ptr: *mut T) -> Option<Self> {
3182 Some(NonNull { pointer: NonZero(ptr as _) })
3188 /// Acquires the underlying `*mut` pointer.
3189 #[stable(feature = "nonnull", since = "1.25.0")]
3190 pub fn as_ptr(self) -> *mut T {
3191 self.pointer.0 as *mut T
3194 /// Dereferences the content.
3196 /// The resulting lifetime is bound to self so this behaves "as if"
3197 /// it were actually an instance of T that is getting borrowed. If a longer
3198 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
3199 #[stable(feature = "nonnull", since = "1.25.0")]
3200 pub unsafe fn as_ref(&self) -> &T {
3204 /// Mutably dereferences the content.
3206 /// The resulting lifetime is bound to self so this behaves "as if"
3207 /// it were actually an instance of T that is getting borrowed. If a longer
3208 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
3209 #[stable(feature = "nonnull", since = "1.25.0")]
3210 pub unsafe fn as_mut(&mut self) -> &mut T {
3214 /// Cast to a pointer of another type
3215 #[stable(feature = "nonnull_cast", since = "1.27.0")]
3216 pub fn cast<U>(self) -> NonNull<U> {
3218 NonNull::new_unchecked(self.as_ptr() as *mut U)
3223 #[stable(feature = "nonnull", since = "1.25.0")]
3224 impl<T: ?Sized> Clone for NonNull<T> {
3225 fn clone(&self) -> Self {
3230 #[stable(feature = "nonnull", since = "1.25.0")]
3231 impl<T: ?Sized> Copy for NonNull<T> { }
3233 #[unstable(feature = "coerce_unsized", issue = "27732")]
3234 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
3236 #[stable(feature = "nonnull", since = "1.25.0")]
3237 impl<T: ?Sized> fmt::Debug for NonNull<T> {
3238 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3239 fmt::Pointer::fmt(&self.as_ptr(), f)
3243 #[stable(feature = "nonnull", since = "1.25.0")]
3244 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
3245 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3246 fmt::Pointer::fmt(&self.as_ptr(), f)
3250 #[stable(feature = "nonnull", since = "1.25.0")]
3251 impl<T: ?Sized> Eq for NonNull<T> {}
3253 #[stable(feature = "nonnull", since = "1.25.0")]
3254 impl<T: ?Sized> PartialEq for NonNull<T> {
3255 fn eq(&self, other: &Self) -> bool {
3256 self.as_ptr() == other.as_ptr()
3260 #[stable(feature = "nonnull", since = "1.25.0")]
3261 impl<T: ?Sized> Ord for NonNull<T> {
3262 fn cmp(&self, other: &Self) -> Ordering {
3263 self.as_ptr().cmp(&other.as_ptr())
3267 #[stable(feature = "nonnull", since = "1.25.0")]
3268 impl<T: ?Sized> PartialOrd for NonNull<T> {
3269 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3270 self.as_ptr().partial_cmp(&other.as_ptr())
3274 #[stable(feature = "nonnull", since = "1.25.0")]
3275 impl<T: ?Sized> hash::Hash for NonNull<T> {
3276 fn hash<H: hash::Hasher>(&self, state: &mut H) {
3277 self.as_ptr().hash(state)
3281 #[unstable(feature = "ptr_internals", issue = "0")]
3282 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
3283 fn from(unique: Unique<T>) -> Self {
3284 NonNull { pointer: unique.pointer }
3288 #[stable(feature = "nonnull", since = "1.25.0")]
3289 impl<'a, T: ?Sized> From<&'a mut T> for NonNull<T> {
3290 fn from(reference: &'a mut T) -> Self {
3291 NonNull { pointer: NonZero(reference as _) }
3295 #[stable(feature = "nonnull", since = "1.25.0")]
3296 impl<'a, T: ?Sized> From<&'a T> for NonNull<T> {
3297 fn from(reference: &'a T) -> Self {
3298 NonNull { pointer: NonZero(reference as _) }