1 //! Manually manage memory through raw pointers.
3 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
7 //! Many functions in this module take raw pointers as arguments and read from
8 //! or write to them. For this to be safe, these pointers must be *valid*.
9 //! Whether a pointer is valid depends on the operation it is used for
10 //! (read or write), and the extent of the memory that is accessed (i.e.,
11 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
12 //! to access only a single value, in which case the documentation omits the size
13 //! and implicitly assumes it to be `size_of::<T>()` bytes.
15 //! The precise rules for validity are not determined yet. The guarantees that are
16 //! provided at this point are very minimal:
18 //! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
19 //! * All pointers (except for the null pointer) are valid for all operations of
21 //! * For a pointer to be valid, it is necessary, but not always sufficient, that the pointer
22 //! be *dereferenceable*: the memory range of the given size starting at the pointer must all be
23 //! within the bounds of a single allocated object. Note that in Rust,
24 //! every (stack-allocated) variable is considered a separate allocated object.
25 //! * All accesses performed by functions in this module are *non-atomic* in the sense
26 //! of [atomic operations] used to synchronize between threads. This means it is
27 //! undefined behavior to perform two concurrent accesses to the same location from different
28 //! threads unless both accesses only read from memory. Notice that this explicitly
29 //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
30 //! be used for inter-thread synchronization.
31 //! * The result of casting a reference to a pointer is valid for as long as the
32 //! underlying object is live and no reference (just raw pointers) is used to
33 //! access the same memory.
35 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
36 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
37 //! will be provided eventually, as the [aliasing] rules are being determined. For more
38 //! information, see the [book] as well as the section in the reference devoted
39 //! to [undefined behavior][ub].
43 //! Valid raw pointers as defined above are not necessarily properly aligned (where
44 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
45 //! aligned to `mem::align_of::<T>()`). However, most functions require their
46 //! arguments to be properly aligned, and will explicitly state
47 //! this requirement in their documentation. Notable exceptions to this are
48 //! [`read_unaligned`] and [`write_unaligned`].
50 //! When a function requires proper alignment, it does so even if the access
51 //! has size 0, i.e., even if memory is not actually touched. Consider using
52 //! [`NonNull::dangling`] in such cases.
54 //! [aliasing]: ../../nomicon/aliasing.html
55 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
56 //! [ub]: ../../reference/behavior-considered-undefined.html
57 //! [null]: ./fn.null.html
58 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
59 //! [atomic operations]: ../../std/sync/atomic/index.html
60 //! [`copy`]: ../../std/ptr/fn.copy.html
61 //! [`offset`]: ../../std/primitive.pointer.html#method.offset
62 //! [`read_unaligned`]: ./fn.read_unaligned.html
63 //! [`write_unaligned`]: ./fn.write_unaligned.html
64 //! [`read_volatile`]: ./fn.read_volatile.html
65 //! [`write_volatile`]: ./fn.write_volatile.html
66 //! [`NonNull::dangling`]: ./struct.NonNull.html#method.dangling
68 #![stable(feature = "rust1", since = "1.0.0")]
70 use crate::cmp
::Ordering
;
73 use crate::intrinsics
::{self, abort, is_aligned_and_not_null, is_nonoverlapping}
;
74 use crate::mem
::{self, MaybeUninit}
;
76 #[stable(feature = "rust1", since = "1.0.0")]
78 pub use crate::intrinsics
::copy_nonoverlapping
;
80 #[stable(feature = "rust1", since = "1.0.0")]
82 pub use crate::intrinsics
::copy
;
84 #[stable(feature = "rust1", since = "1.0.0")]
86 pub use crate::intrinsics
::write_bytes
;
89 #[stable(feature = "nonnull", since = "1.25.0")]
90 pub use non_null
::NonNull
;
93 #[unstable(feature = "ptr_internals", issue = "none")]
94 pub use unique
::Unique
;
99 /// Executes the destructor (if any) of the pointed-to value.
101 /// This is semantically equivalent to calling [`ptr::read`] and discarding
102 /// the result, but has the following advantages:
104 /// * It is *required* to use `drop_in_place` to drop unsized types like
105 /// trait objects, because they can't be read out onto the stack and
106 /// dropped normally.
108 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
109 /// dropping manually allocated memory (e.g., when writing Box/Rc/Vec),
110 /// as the compiler doesn't need to prove that it's sound to elide the
113 /// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
114 /// (pinned data must not be moved before it is dropped).
116 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
117 /// location first using [`ptr::read_unaligned`]. For packed structs, this move is
118 /// done automatically by the compiler. This means the fields of packed structs
119 /// are not dropped in-place.
121 /// [`ptr::read`]: ../ptr/fn.read.html
122 /// [`ptr::read_unaligned`]: ../ptr/fn.read_unaligned.html
123 /// [pinned]: ../pin/index.html
127 /// Behavior is undefined if any of the following conditions are violated:
129 /// * `to_drop` must be [valid] for both reads and writes.
131 /// * `to_drop` must be properly aligned.
133 /// * The value `to_drop` points to must be valid for dropping, which may mean it must uphold
134 /// additional invariants - this is type-dependent.
136 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
137 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
138 /// foo` counts as a use because it will cause the value to be dropped
139 /// again. [`write`] can be used to overwrite data without causing it to be
142 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
144 /// [valid]: ../ptr/index.html#safety
145 /// [`Copy`]: ../marker/trait.Copy.html
146 /// [`write`]: ../ptr/fn.write.html
150 /// Manually remove the last item from a vector:
156 /// let last = Rc::new(1);
157 /// let weak = Rc::downgrade(&last);
159 /// let mut v = vec![Rc::new(0), last];
162 /// // Get a raw pointer to the last element in `v`.
163 /// let ptr = &mut v[1] as *mut _;
164 /// // Shorten `v` to prevent the last item from being dropped. We do that first,
165 /// // to prevent issues if the `drop_in_place` below panics.
167 /// // Without a call `drop_in_place`, the last item would never be dropped,
168 /// // and the memory it manages would be leaked.
169 /// ptr::drop_in_place(ptr);
172 /// assert_eq!(v, &[0.into()]);
174 /// // Ensure that the last item was dropped.
175 /// assert!(weak.upgrade().is_none());
178 /// Notice that the compiler performs this copy automatically when dropping packed structs,
179 /// i.e., you do not usually have to worry about such issues unless you call `drop_in_place`
181 #[stable(feature = "drop_in_place", since = "1.8.0")]
182 #[lang = "drop_in_place"]
183 #[allow(unconditional_recursion)]
184 pub unsafe fn drop_in_place
<T
: ?Sized
>(to_drop
: *mut T
) {
185 // Code here does not matter - this is replaced by the
186 // real drop glue by the compiler.
188 // SAFETY: see comment above
189 unsafe { drop_in_place(to_drop) }
192 /// Creates a null raw pointer.
199 /// let p: *const i32 = ptr::null();
200 /// assert!(p.is_null());
203 #[stable(feature = "rust1", since = "1.0.0")]
205 #[rustc_const_stable(feature = "const_ptr_null", since = "1.32.0")]
206 pub const fn null
<T
>() -> *const T
{
210 /// Creates a null mutable raw pointer.
217 /// let p: *mut i32 = ptr::null_mut();
218 /// assert!(p.is_null());
221 #[stable(feature = "rust1", since = "1.0.0")]
223 #[rustc_const_stable(feature = "const_ptr_null", since = "1.32.0")]
224 pub const fn null_mut
<T
>() -> *mut T
{
229 pub(crate) union Repr
<T
> {
230 pub(crate) rust
: *const [T
],
232 pub(crate) raw
: FatPtr
<T
>,
236 pub(crate) struct FatPtr
<T
> {
238 pub(crate) len
: usize,
241 /// Forms a raw slice from a pointer and a length.
243 /// The `len` argument is the number of **elements**, not the number of bytes.
245 /// This function is safe, but actually using the return value is unsafe.
246 /// See the documentation of [`from_raw_parts`] for slice safety requirements.
248 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
255 /// // create a slice pointer when starting out with a pointer to the first element
256 /// let x = [5, 6, 7];
257 /// let raw_pointer = x.as_ptr();
258 /// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
259 /// assert_eq!(unsafe { &*slice }[2], 7);
262 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
263 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
264 pub const fn slice_from_raw_parts
<T
>(data
: *const T
, len
: usize) -> *const [T
] {
265 // SAFETY: Accessing the value from the `Repr` union is safe since *const [T]
266 // and FatPtr have the same memory layouts. Only std can make this
268 unsafe { Repr { raw: FatPtr { data, len }
}.rust
}
271 /// Performs the same functionality as [`slice_from_raw_parts`], except that a
272 /// raw mutable slice is returned, as opposed to a raw immutable slice.
274 /// See the documentation of [`slice_from_raw_parts`] for more details.
276 /// This function is safe, but actually using the return value is unsafe.
277 /// See the documentation of [`from_raw_parts_mut`] for slice safety requirements.
279 /// [`slice_from_raw_parts`]: fn.slice_from_raw_parts.html
280 /// [`from_raw_parts_mut`]: ../../std/slice/fn.from_raw_parts_mut.html
287 /// let x = &mut [5, 6, 7];
288 /// let raw_pointer = x.as_mut_ptr();
289 /// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
292 /// (*slice)[2] = 99; // assign a value at an index in the slice
295 /// assert_eq!(unsafe { &*slice }[2], 99);
298 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
299 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
300 pub const fn slice_from_raw_parts_mut
<T
>(data
: *mut T
, len
: usize) -> *mut [T
] {
301 // SAFETY: Accessing the value from the `Repr` union is safe since *mut [T]
302 // and FatPtr have the same memory layouts
303 unsafe { Repr { raw: FatPtr { data, len }
}.rust_mut
}
306 /// Swaps the values at two mutable locations of the same type, without
307 /// deinitializing either.
309 /// But for the following two exceptions, this function is semantically
310 /// equivalent to [`mem::swap`]:
312 /// * It operates on raw pointers instead of references. When references are
313 /// available, [`mem::swap`] should be preferred.
315 /// * The two pointed-to values may overlap. If the values do overlap, then the
316 /// overlapping region of memory from `x` will be used. This is demonstrated
317 /// in the second example below.
319 /// [`mem::swap`]: ../mem/fn.swap.html
323 /// Behavior is undefined if any of the following conditions are violated:
325 /// * Both `x` and `y` must be [valid] for both reads and writes.
327 /// * Both `x` and `y` must be properly aligned.
329 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
331 /// [valid]: ../ptr/index.html#safety
335 /// Swapping two non-overlapping regions:
340 /// let mut array = [0, 1, 2, 3];
342 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
343 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
347 /// assert_eq!([2, 3, 0, 1], array);
351 /// Swapping two overlapping regions:
356 /// let mut array = [0, 1, 2, 3];
358 /// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; // this is `array[0..3]`
359 /// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; // this is `array[1..4]`
363 /// // The indices `1..3` of the slice overlap between `x` and `y`.
364 /// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
365 /// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
366 /// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
367 /// // This implementation is defined to make the latter choice.
368 /// assert_eq!([1, 0, 1, 2], array);
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub unsafe fn swap
<T
>(x
: *mut T
, y
: *mut T
) {
374 // Give ourselves some scratch space to work with.
375 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
376 let mut tmp
= MaybeUninit
::<T
>::uninit();
379 // SAFETY: the caller must guarantee that `x` and `y` are
380 // valid for writes and properly aligned. `tmp` cannot be
381 // overlapping either `x` or `y` because `tmp` was just allocated
382 // on the stack as a separate allocated object.
384 copy_nonoverlapping(x
, tmp
.as_mut_ptr(), 1);
385 copy(y
, x
, 1); // `x` and `y` may overlap
386 copy_nonoverlapping(tmp
.as_ptr(), y
, 1);
390 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
391 /// beginning at `x` and `y`. The two regions must *not* overlap.
395 /// Behavior is undefined if any of the following conditions are violated:
397 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
398 /// size_of::<T>()` bytes.
400 /// * Both `x` and `y` must be properly aligned.
402 /// * The region of memory beginning at `x` with a size of `count *
403 /// size_of::<T>()` bytes must *not* overlap with the region of memory
404 /// beginning at `y` with the same size.
406 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
407 /// the pointers must be non-NULL and properly aligned.
409 /// [valid]: ../ptr/index.html#safety
418 /// let mut x = [1, 2, 3, 4];
419 /// let mut y = [7, 8, 9];
422 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
425 /// assert_eq!(x, [7, 8, 3, 4]);
426 /// assert_eq!(y, [1, 2, 9]);
429 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
430 pub unsafe fn swap_nonoverlapping
<T
>(x
: *mut T
, y
: *mut T
, count
: usize) {
431 if cfg
!(debug_assertions
)
432 && !(is_aligned_and_not_null(x
)
433 && is_aligned_and_not_null(y
)
434 && is_nonoverlapping(x
, y
, count
))
436 // Not panicking to keep codegen impact smaller.
440 let x
= x
as *mut u8;
441 let y
= y
as *mut u8;
442 let len
= mem
::size_of
::<T
>() * count
;
443 // SAFETY: the caller must guarantee that `x` and `y` are
444 // valid for writes and properly aligned.
445 unsafe { swap_nonoverlapping_bytes(x, y, len) }
449 pub(crate) unsafe fn swap_nonoverlapping_one
<T
>(x
: *mut T
, y
: *mut T
) {
450 // For types smaller than the block optimization below,
451 // just swap directly to avoid pessimizing codegen.
452 if mem
::size_of
::<T
>() < 32 {
453 // SAFETY: the caller must guarantee that `x` and `y` are valid
454 // for writes, properly aligned, and non-overlapping.
457 copy_nonoverlapping(y
, x
, 1);
461 // SAFETY: the caller must uphold the safety contract for `swap_nonoverlapping`.
462 unsafe { swap_nonoverlapping(x, y, 1) }
;
467 unsafe fn swap_nonoverlapping_bytes(x
: *mut u8, y
: *mut u8, len
: usize) {
468 // The approach here is to utilize simd to swap x & y efficiently. Testing reveals
469 // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel
470 // Haswell E processors. LLVM is more able to optimize if we give a struct a
471 // #[repr(simd)], even if we don't actually use this struct directly.
473 // FIXME repr(simd) broken on emscripten and redox
474 #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))]
475 struct Block(u64, u64, u64, u64);
476 struct UnalignedBlock(u64, u64, u64, u64);
478 let block_size
= mem
::size_of
::<Block
>();
480 // Loop through x & y, copying them `Block` at a time
481 // The optimizer should unroll the loop fully for most types
482 // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively
484 while i
+ block_size
<= len
{
485 // Create some uninitialized memory as scratch space
486 // Declaring `t` here avoids aligning the stack when this loop is unused
487 let mut t
= mem
::MaybeUninit
::<Block
>::uninit();
488 let t
= t
.as_mut_ptr() as *mut u8;
490 // SAFETY: As `i < len`, and as the caller must guarantee that `x` and `y` are valid
491 // for `len` bytes, `x + i` and `y + i` must be valid adresses, which fulfills the
492 // safety contract for `add`.
494 // Also, the caller must guarantee that `x` and `y` are valid for writes, properly aligned,
495 // and non-overlapping, which fulfills the safety contract for `copy_nonoverlapping`.
500 // Swap a block of bytes of x & y, using t as a temporary buffer
501 // This should be optimized into efficient SIMD operations where available
502 copy_nonoverlapping(x
, t
, block_size
);
503 copy_nonoverlapping(y
, x
, block_size
);
504 copy_nonoverlapping(t
, y
, block_size
);
510 // Swap any remaining bytes
511 let mut t
= mem
::MaybeUninit
::<UnalignedBlock
>::uninit();
514 let t
= t
.as_mut_ptr() as *mut u8;
516 // SAFETY: see previous safety comment.
521 copy_nonoverlapping(x
, t
, rem
);
522 copy_nonoverlapping(y
, x
, rem
);
523 copy_nonoverlapping(t
, y
, rem
);
528 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
530 /// Neither value is dropped.
532 /// This function is semantically equivalent to [`mem::replace`] except that it
533 /// operates on raw pointers instead of references. When references are
534 /// available, [`mem::replace`] should be preferred.
536 /// [`mem::replace`]: ../mem/fn.replace.html
540 /// Behavior is undefined if any of the following conditions are violated:
542 /// * `dst` must be [valid] for both reads and writes.
544 /// * `dst` must be properly aligned.
546 /// * `dst` must point to a properly initialized value of type `T`.
548 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
550 /// [valid]: ../ptr/index.html#safety
557 /// let mut rust = vec!['b', 'u', 's', 't'];
559 /// // `mem::replace` would have the same effect without requiring the unsafe
562 /// ptr::replace(&mut rust[0], 'r')
565 /// assert_eq!(b, 'b');
566 /// assert_eq!(rust, &['r', 'u', 's', 't']);
569 #[stable(feature = "rust1", since = "1.0.0")]
570 pub unsafe fn replace
<T
>(dst
: *mut T
, mut src
: T
) -> T
{
571 // SAFETY: the caller must guarantee that `dst` is valid to be
572 // cast to a mutable reference (valid for writes, aligned, initialized),
573 // and cannot overlap `src` since `dst` must point to a distinct
576 mem
::swap(&mut *dst
, &mut src
); // cannot overlap
581 /// Reads the value from `src` without moving it. This leaves the
582 /// memory in `src` unchanged.
586 /// Behavior is undefined if any of the following conditions are violated:
588 /// * `src` must be [valid] for reads.
590 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
593 /// * `src` must point to a properly initialized value of type `T`.
595 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
603 /// let y = &x as *const i32;
606 /// assert_eq!(std::ptr::read(y), 12);
610 /// Manually implement [`mem::swap`]:
615 /// fn swap<T>(a: &mut T, b: &mut T) {
617 /// // Create a bitwise copy of the value at `a` in `tmp`.
618 /// let tmp = ptr::read(a);
620 /// // Exiting at this point (either by explicitly returning or by
621 /// // calling a function which panics) would cause the value in `tmp` to
622 /// // be dropped while the same value is still referenced by `a`. This
623 /// // could trigger undefined behavior if `T` is not `Copy`.
625 /// // Create a bitwise copy of the value at `b` in `a`.
626 /// // This is safe because mutable references cannot alias.
627 /// ptr::copy_nonoverlapping(b, a, 1);
629 /// // As above, exiting here could trigger undefined behavior because
630 /// // the same value is referenced by `a` and `b`.
632 /// // Move `tmp` into `b`.
633 /// ptr::write(b, tmp);
635 /// // `tmp` has been moved (`write` takes ownership of its second argument),
636 /// // so nothing is dropped implicitly here.
640 /// let mut foo = "foo".to_owned();
641 /// let mut bar = "bar".to_owned();
643 /// swap(&mut foo, &mut bar);
645 /// assert_eq!(foo, "bar");
646 /// assert_eq!(bar, "foo");
649 /// ## Ownership of the Returned Value
651 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
652 /// If `T` is not [`Copy`], using both the returned value and the value at
653 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
654 /// use because it will attempt to drop the value at `*src`.
656 /// [`write`] can be used to overwrite data without causing it to be dropped.
661 /// let mut s = String::from("foo");
663 /// // `s2` now points to the same underlying memory as `s`.
664 /// let mut s2: String = ptr::read(&s);
666 /// assert_eq!(s2, "foo");
668 /// // Assigning to `s2` causes its original value to be dropped. Beyond
669 /// // this point, `s` must no longer be used, as the underlying memory has
671 /// s2 = String::default();
672 /// assert_eq!(s2, "");
674 /// // Assigning to `s` would cause the old value to be dropped again,
675 /// // resulting in undefined behavior.
676 /// // s = String::from("bar"); // ERROR
678 /// // `ptr::write` can be used to overwrite a value without dropping it.
679 /// ptr::write(&mut s, String::from("bar"));
682 /// assert_eq!(s, "bar");
685 /// [`mem::swap`]: ../mem/fn.swap.html
686 /// [valid]: ../ptr/index.html#safety
687 /// [`Copy`]: ../marker/trait.Copy.html
688 /// [`read_unaligned`]: ./fn.read_unaligned.html
689 /// [`write`]: ./fn.write.html
691 #[stable(feature = "rust1", since = "1.0.0")]
692 pub unsafe fn read
<T
>(src
: *const T
) -> T
{
693 // `copy_nonoverlapping` takes care of debug_assert.
694 let mut tmp
= MaybeUninit
::<T
>::uninit();
695 // SAFETY: the caller must guarantee that `src` is valid for reads.
696 // `src` cannot overlap `tmp` because `tmp` was just allocated on
697 // the stack as a separate allocated object.
699 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
700 // to be properly initialized.
702 copy_nonoverlapping(src
, tmp
.as_mut_ptr(), 1);
707 /// Reads the value from `src` without moving it. This leaves the
708 /// memory in `src` unchanged.
710 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
714 /// Behavior is undefined if any of the following conditions are violated:
716 /// * `src` must be [valid] for reads.
718 /// * `src` must point to a properly initialized value of type `T`.
720 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
721 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
722 /// value and the value at `*src` can [violate memory safety][read-ownership].
724 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
726 /// [`Copy`]: ../marker/trait.Copy.html
727 /// [`read`]: ./fn.read.html
728 /// [`write_unaligned`]: ./fn.write_unaligned.html
729 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
730 /// [valid]: ../ptr/index.html#safety
732 /// ## On `packed` structs
734 /// It is currently impossible to create raw pointers to unaligned fields
735 /// of a packed struct.
737 /// Attempting to create a raw pointer to an `unaligned` struct field with
738 /// an expression such as `&packed.unaligned as *const FieldType` creates an
739 /// intermediate unaligned reference before converting that to a raw pointer.
740 /// That this reference is temporary and immediately cast is inconsequential
741 /// as the compiler always expects references to be properly aligned.
742 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
743 /// *undefined behavior* in your program.
745 /// An example of what not to do and how this relates to `read_unaligned` is:
748 /// #[repr(packed, C)]
754 /// let packed = Packed {
756 /// unaligned: 0x01020304,
760 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
762 /// // A temporary unaligned reference is created here which results in
763 /// // undefined behavior regardless of whether the reference is used or not.
764 /// &packed.unaligned
765 /// // Casting to a raw pointer doesn't help; the mistake already happened.
768 /// let v = std::ptr::read_unaligned(unaligned);
774 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
775 // FIXME: Update docs based on outcome of RFC #2582 and friends.
779 /// Read an usize value from a byte buffer:
784 /// fn read_usize(x: &[u8]) -> usize {
785 /// assert!(x.len() >= mem::size_of::<usize>());
787 /// let ptr = x.as_ptr() as *const usize;
789 /// unsafe { ptr.read_unaligned() }
793 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
794 pub unsafe fn read_unaligned
<T
>(src
: *const T
) -> T
{
795 // `copy_nonoverlapping` takes care of debug_assert.
796 let mut tmp
= MaybeUninit
::<T
>::uninit();
797 // SAFETY: the caller must guarantee that `src` is valid for reads.
798 // `src` cannot overlap `tmp` because `tmp` was just allocated on
799 // the stack as a separate allocated object.
801 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
802 // to be properly initialized.
804 copy_nonoverlapping(src
as *const u8, tmp
.as_mut_ptr() as *mut u8, mem
::size_of
::<T
>());
809 /// Overwrites a memory location with the given value without reading or
810 /// dropping the old value.
812 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
813 /// allocations or resources, so care should be taken not to overwrite an object
814 /// that should be dropped.
816 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
817 /// location pointed to by `dst`.
819 /// This is appropriate for initializing uninitialized memory, or overwriting
820 /// memory that has previously been [`read`] from.
822 /// [`read`]: ./fn.read.html
826 /// Behavior is undefined if any of the following conditions are violated:
828 /// * `dst` must be [valid] for writes.
830 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
833 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
835 /// [valid]: ../ptr/index.html#safety
836 /// [`write_unaligned`]: ./fn.write_unaligned.html
844 /// let y = &mut x as *mut i32;
848 /// std::ptr::write(y, z);
849 /// assert_eq!(std::ptr::read(y), 12);
853 /// Manually implement [`mem::swap`]:
858 /// fn swap<T>(a: &mut T, b: &mut T) {
860 /// // Create a bitwise copy of the value at `a` in `tmp`.
861 /// let tmp = ptr::read(a);
863 /// // Exiting at this point (either by explicitly returning or by
864 /// // calling a function which panics) would cause the value in `tmp` to
865 /// // be dropped while the same value is still referenced by `a`. This
866 /// // could trigger undefined behavior if `T` is not `Copy`.
868 /// // Create a bitwise copy of the value at `b` in `a`.
869 /// // This is safe because mutable references cannot alias.
870 /// ptr::copy_nonoverlapping(b, a, 1);
872 /// // As above, exiting here could trigger undefined behavior because
873 /// // the same value is referenced by `a` and `b`.
875 /// // Move `tmp` into `b`.
876 /// ptr::write(b, tmp);
878 /// // `tmp` has been moved (`write` takes ownership of its second argument),
879 /// // so nothing is dropped implicitly here.
883 /// let mut foo = "foo".to_owned();
884 /// let mut bar = "bar".to_owned();
886 /// swap(&mut foo, &mut bar);
888 /// assert_eq!(foo, "bar");
889 /// assert_eq!(bar, "foo");
892 /// [`mem::swap`]: ../mem/fn.swap.html
894 #[stable(feature = "rust1", since = "1.0.0")]
895 pub unsafe fn write
<T
>(dst
: *mut T
, src
: T
) {
896 if cfg
!(debug_assertions
) && !is_aligned_and_not_null(dst
) {
897 // Not panicking to keep codegen impact smaller.
900 // SAFETY: the caller must uphold the safety contract for `move_val_init`.
901 unsafe { intrinsics::move_val_init(&mut *dst, src) }
904 /// Overwrites a memory location with the given value without reading or
905 /// dropping the old value.
907 /// Unlike [`write`], the pointer may be unaligned.
909 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
910 /// could leak allocations or resources, so care should be taken not to overwrite
911 /// an object that should be dropped.
913 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
914 /// location pointed to by `dst`.
916 /// This is appropriate for initializing uninitialized memory, or overwriting
917 /// memory that has previously been read with [`read_unaligned`].
919 /// [`write`]: ./fn.write.html
920 /// [`read_unaligned`]: ./fn.read_unaligned.html
924 /// Behavior is undefined if any of the following conditions are violated:
926 /// * `dst` must be [valid] for writes.
928 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
930 /// [valid]: ../ptr/index.html#safety
932 /// ## On `packed` structs
934 /// It is currently impossible to create raw pointers to unaligned fields
935 /// of a packed struct.
937 /// Attempting to create a raw pointer to an `unaligned` struct field with
938 /// an expression such as `&packed.unaligned as *const FieldType` creates an
939 /// intermediate unaligned reference before converting that to a raw pointer.
940 /// That this reference is temporary and immediately cast is inconsequential
941 /// as the compiler always expects references to be properly aligned.
942 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
943 /// *undefined behavior* in your program.
945 /// An example of what not to do and how this relates to `write_unaligned` is:
948 /// #[repr(packed, C)]
954 /// let v = 0x01020304;
955 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
958 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
960 /// // A temporary unaligned reference is created here which results in
961 /// // undefined behavior regardless of whether the reference is used or not.
962 /// &mut packed.unaligned
963 /// // Casting to a raw pointer doesn't help; the mistake already happened.
966 /// std::ptr::write_unaligned(unaligned, v);
972 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
973 // FIXME: Update docs based on outcome of RFC #2582 and friends.
977 /// Write an usize value to a byte buffer:
982 /// fn write_usize(x: &mut [u8], val: usize) {
983 /// assert!(x.len() >= mem::size_of::<usize>());
985 /// let ptr = x.as_mut_ptr() as *mut usize;
987 /// unsafe { ptr.write_unaligned(val) }
991 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
992 pub unsafe fn write_unaligned
<T
>(dst
: *mut T
, src
: T
) {
993 // SAFETY: the caller must guarantee that `dst` is valid for writes.
994 // `dst` cannot overlap `src` because the caller has mutable access
995 // to `dst` while `src` is owned by this function.
997 // `copy_nonoverlapping` takes care of debug_assert.
998 copy_nonoverlapping(&src
as *const T
as *const u8, dst
as *mut u8, mem
::size_of
::<T
>());
1003 /// Performs a volatile read of the value from `src` without moving it. This
1004 /// leaves the memory in `src` unchanged.
1006 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1007 /// to not be elided or reordered by the compiler across other volatile
1010 /// [`write_volatile`]: ./fn.write_volatile.html
1014 /// Rust does not currently have a rigorously and formally defined memory model,
1015 /// so the precise semantics of what "volatile" means here is subject to change
1016 /// over time. That being said, the semantics will almost always end up pretty
1017 /// similar to [C11's definition of volatile][c11].
1019 /// The compiler shouldn't change the relative order or number of volatile
1020 /// memory operations. However, volatile memory operations on zero-sized types
1021 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
1022 /// and may be ignored.
1024 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1028 /// Behavior is undefined if any of the following conditions are violated:
1030 /// * `src` must be [valid] for reads.
1032 /// * `src` must be properly aligned.
1034 /// * `src` must point to a properly initialized value of type `T`.
1036 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
1037 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1038 /// value and the value at `*src` can [violate memory safety][read-ownership].
1039 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
1042 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
1044 /// [valid]: ../ptr/index.html#safety
1045 /// [`Copy`]: ../marker/trait.Copy.html
1046 /// [`read`]: ./fn.read.html
1047 /// [read-ownership]: ./fn.read.html#ownership-of-the-returned-value
1049 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1050 /// on questions involving concurrent access from multiple threads. Volatile
1051 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1052 /// a race between a `read_volatile` and any write operation to the same location
1053 /// is undefined behavior.
1061 /// let y = &x as *const i32;
1064 /// assert_eq!(std::ptr::read_volatile(y), 12);
1068 #[stable(feature = "volatile", since = "1.9.0")]
1069 pub unsafe fn read_volatile
<T
>(src
: *const T
) -> T
{
1070 if cfg
!(debug_assertions
) && !is_aligned_and_not_null(src
) {
1071 // Not panicking to keep codegen impact smaller.
1074 // SAFETY: the caller must uphold the safety contract for `volatile_load`.
1075 unsafe { intrinsics::volatile_load(src) }
1078 /// Performs a volatile write of a memory location with the given value without
1079 /// reading or dropping the old value.
1081 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1082 /// to not be elided or reordered by the compiler across other volatile
1085 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
1086 /// could leak allocations or resources, so care should be taken not to overwrite
1087 /// an object that should be dropped.
1089 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1090 /// location pointed to by `dst`.
1092 /// [`read_volatile`]: ./fn.read_volatile.html
1096 /// Rust does not currently have a rigorously and formally defined memory model,
1097 /// so the precise semantics of what "volatile" means here is subject to change
1098 /// over time. That being said, the semantics will almost always end up pretty
1099 /// similar to [C11's definition of volatile][c11].
1101 /// The compiler shouldn't change the relative order or number of volatile
1102 /// memory operations. However, volatile memory operations on zero-sized types
1103 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
1104 /// and may be ignored.
1106 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1110 /// Behavior is undefined if any of the following conditions are violated:
1112 /// * `dst` must be [valid] for writes.
1114 /// * `dst` must be properly aligned.
1116 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
1118 /// [valid]: ../ptr/index.html#safety
1120 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1121 /// on questions involving concurrent access from multiple threads. Volatile
1122 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1123 /// a race between a `write_volatile` and any other operation (reading or writing)
1124 /// on the same location is undefined behavior.
1132 /// let y = &mut x as *mut i32;
1136 /// std::ptr::write_volatile(y, z);
1137 /// assert_eq!(std::ptr::read_volatile(y), 12);
1141 #[stable(feature = "volatile", since = "1.9.0")]
1142 pub unsafe fn write_volatile
<T
>(dst
: *mut T
, src
: T
) {
1143 if cfg
!(debug_assertions
) && !is_aligned_and_not_null(dst
) {
1144 // Not panicking to keep codegen impact smaller.
1147 // SAFETY: the caller must uphold the safety contract for `volatile_store`.
1149 intrinsics
::volatile_store(dst
, src
);
1153 /// Align pointer `p`.
1155 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
1156 /// to pointer `p` so that pointer `p` would get aligned to `a`.
1158 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
1159 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
1162 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
1163 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
1164 /// than trying to adapt this to accommodate that change.
1166 /// Any questions go to @nagisa.
1167 #[lang = "align_offset"]
1168 pub(crate) unsafe fn align_offset
<T
: Sized
>(p
: *const T
, a
: usize) -> usize {
1169 /// Calculate multiplicative modular inverse of `x` modulo `m`.
1171 /// This implementation is tailored for align_offset and has following preconditions:
1173 /// * `m` is a power-of-two;
1174 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1176 /// Implementation of this function shall not panic. Ever.
1178 fn mod_inv(x
: usize, m
: usize) -> usize {
1179 /// Multiplicative modular inverse table modulo 2⁴ = 16.
1181 /// Note, that this table does not contain values where inverse does not exist (i.e., for
1182 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
1183 const INV_TABLE_MOD_16
: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
1184 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
1185 const INV_TABLE_MOD
: usize = 16;
1187 const INV_TABLE_MOD_SQUARED
: usize = INV_TABLE_MOD
* INV_TABLE_MOD
;
1189 let table_inverse
= INV_TABLE_MOD_16
[(x
& (INV_TABLE_MOD
- 1)) >> 1] as usize;
1190 if m
<= INV_TABLE_MOD
{
1191 table_inverse
& (m
- 1)
1193 // We iterate "up" using the following formula:
1195 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1197 // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
1198 let mut inverse
= table_inverse
;
1199 let mut going_mod
= INV_TABLE_MOD_SQUARED
;
1201 // y = y * (2 - xy) mod n
1203 // Note, that we use wrapping operations here intentionally – the original formula
1204 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
1205 // usize::MAX` instead, because we take the result `mod n` at the end
1207 inverse
= inverse
.wrapping_mul(2usize
.wrapping_sub(x
.wrapping_mul(inverse
)));
1209 return inverse
& (m
- 1);
1211 going_mod
= going_mod
.wrapping_mul(going_mod
);
1216 let stride
= mem
::size_of
::<T
>();
1217 let a_minus_one
= a
.wrapping_sub(1);
1218 let pmoda
= p
as usize & a_minus_one
;
1221 // Already aligned. Yay!
1226 return if stride
== 0 {
1227 // If the pointer is not aligned, and the element is zero-sized, then no amount of
1228 // elements will ever align the pointer.
1231 a
.wrapping_sub(pmoda
)
1235 let smoda
= stride
& a_minus_one
;
1236 // SAFETY: a is power-of-two so cannot be 0. stride = 0 is handled above.
1237 let gcdpow
= unsafe { intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)) }
;
1238 let gcd
= 1usize
<< gcdpow
;
1240 if p
as usize & (gcd
.wrapping_sub(1)) == 0 {
1241 // This branch solves for the following linear congruence equation:
1243 // ` p + so = 0 mod a `
1245 // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1246 // requested alignment.
1248 // With `g = gcd(a, s)`, and the above asserting that `p` is also divisible by `g`, we can
1249 // denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1251 // ` p' + s'o = 0 mod a' `
1252 // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1254 // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the second
1255 // term is "how does incrementing `p` by `s` bytes change the relative alignment of `p`" (again
1257 // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1260 // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1261 // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`.
1262 let a2
= a
>> gcdpow
;
1263 let a2minus1
= a2
.wrapping_sub(1);
1264 let s2
= smoda
>> gcdpow
;
1265 let minusp2
= a2
.wrapping_sub(pmoda
>> gcdpow
);
1266 return (minusp2
.wrapping_mul(mod_inv(s2
, a2
))) & a2minus1
;
1269 // Cannot be aligned at all.
1273 /// Compares raw pointers for equality.
1275 /// This is the same as using the `==` operator, but less generic:
1276 /// the arguments have to be `*const T` raw pointers,
1277 /// not anything that implements `PartialEq`.
1279 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
1280 /// by their address rather than comparing the values they point to
1281 /// (which is what the `PartialEq for &T` implementation does).
1289 /// let other_five = 5;
1290 /// let five_ref = &five;
1291 /// let same_five_ref = &five;
1292 /// let other_five_ref = &other_five;
1294 /// assert!(five_ref == same_five_ref);
1295 /// assert!(ptr::eq(five_ref, same_five_ref));
1297 /// assert!(five_ref == other_five_ref);
1298 /// assert!(!ptr::eq(five_ref, other_five_ref));
1301 /// Slices are also compared by their length (fat pointers):
1304 /// let a = [1, 2, 3];
1305 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
1306 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
1307 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
1310 /// Traits are also compared by their implementation:
1313 /// #[repr(transparent)]
1314 /// struct Wrapper { member: i32 }
1317 /// impl Trait for Wrapper {}
1318 /// impl Trait for i32 {}
1320 /// let wrapper = Wrapper { member: 10 };
1322 /// // Pointers have equal addresses.
1323 /// assert!(std::ptr::eq(
1324 /// &wrapper as *const Wrapper as *const u8,
1325 /// &wrapper.member as *const i32 as *const u8
1328 /// // Objects have equal addresses, but `Trait` has different implementations.
1329 /// assert!(!std::ptr::eq(
1330 /// &wrapper as &dyn Trait,
1331 /// &wrapper.member as &dyn Trait,
1333 /// assert!(!std::ptr::eq(
1334 /// &wrapper as &dyn Trait as *const dyn Trait,
1335 /// &wrapper.member as &dyn Trait as *const dyn Trait,
1338 /// // Converting the reference to a `*const u8` compares by address.
1339 /// assert!(std::ptr::eq(
1340 /// &wrapper as &dyn Trait as *const dyn Trait as *const u8,
1341 /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
1344 #[stable(feature = "ptr_eq", since = "1.17.0")]
1346 pub fn eq
<T
: ?Sized
>(a
: *const T
, b
: *const T
) -> bool
{
1350 /// Hash a raw pointer.
1352 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
1353 /// by its address rather than the value it points to
1354 /// (which is what the `Hash for &T` implementation does).
1359 /// use std::collections::hash_map::DefaultHasher;
1360 /// use std::hash::{Hash, Hasher};
1364 /// let five_ref = &five;
1366 /// let mut hasher = DefaultHasher::new();
1367 /// ptr::hash(five_ref, &mut hasher);
1368 /// let actual = hasher.finish();
1370 /// let mut hasher = DefaultHasher::new();
1371 /// (five_ref as *const i32).hash(&mut hasher);
1372 /// let expected = hasher.finish();
1374 /// assert_eq!(actual, expected);
1376 #[stable(feature = "ptr_hash", since = "1.35.0")]
1377 pub fn hash
<T
: ?Sized
, S
: hash
::Hasher
>(hashee
: *const T
, into
: &mut S
) {
1378 use crate::hash
::Hash
;
1382 // Impls for function pointers
1383 macro_rules
! fnptr_impls_safety_abi
{
1384 ($FnTy
: ty
, $
($Arg
: ident
),*) => {
1385 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1386 impl<Ret
, $
($Arg
),*> PartialEq
for $FnTy
{
1388 fn eq(&self, other
: &Self) -> bool
{
1389 *self as usize == *other
as usize
1393 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1394 impl<Ret
, $
($Arg
),*> Eq
for $FnTy {}
1396 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1397 impl<Ret
, $
($Arg
),*> PartialOrd
for $FnTy
{
1399 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
1400 (*self as usize).partial_cmp(&(*other
as usize))
1404 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1405 impl<Ret
, $
($Arg
),*> Ord
for $FnTy
{
1407 fn cmp(&self, other
: &Self) -> Ordering
{
1408 (*self as usize).cmp(&(*other
as usize))
1412 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1413 impl<Ret
, $
($Arg
),*> hash
::Hash
for $FnTy
{
1414 fn hash
<HH
: hash
::Hasher
>(&self, state
: &mut HH
) {
1415 state
.write_usize(*self as usize)
1419 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1420 impl<Ret
, $
($Arg
),*> fmt
::Pointer
for $FnTy
{
1421 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1422 // HACK: The intermediate cast as usize is required for AVR
1423 // so that the address space of the source function pointer
1424 // is preserved in the final function pointer.
1426 // https://github.com/avr-rust/rust/issues/143
1427 fmt
::Pointer
::fmt(&(*self as usize as *const ()), f
)
1431 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1432 impl<Ret
, $
($Arg
),*> fmt
::Debug
for $FnTy
{
1433 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1434 // HACK: The intermediate cast as usize is required for AVR
1435 // so that the address space of the source function pointer
1436 // is preserved in the final function pointer.
1438 // https://github.com/avr-rust/rust/issues/143
1439 fmt
::Pointer
::fmt(&(*self as usize as *const ()), f
)
1445 macro_rules
! fnptr_impls_args
{
1446 ($
($Arg
: ident
),+) => {
1447 fnptr_impls_safety_abi
! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1448 fnptr_impls_safety_abi
! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1449 fnptr_impls_safety_abi
! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1450 fnptr_impls_safety_abi
! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1451 fnptr_impls_safety_abi
! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1452 fnptr_impls_safety_abi
! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1455 // No variadic functions with 0 parameters
1456 fnptr_impls_safety_abi
! { extern "Rust" fn() -> Ret, }
1457 fnptr_impls_safety_abi
! { extern "C" fn() -> Ret, }
1458 fnptr_impls_safety_abi
! { unsafe extern "Rust" fn() -> Ret, }
1459 fnptr_impls_safety_abi
! { unsafe extern "C" fn() -> Ret, }
1463 fnptr_impls_args
! {}
1464 fnptr_impls_args
! { A }
1465 fnptr_impls_args
! { A, B }
1466 fnptr_impls_args
! { A, B, C }
1467 fnptr_impls_args
! { A, B, C, D }
1468 fnptr_impls_args
! { A, B, C, D, E }
1469 fnptr_impls_args
! { A, B, C, D, E, F }
1470 fnptr_impls_args
! { A, B, C, D, E, F, G }
1471 fnptr_impls_args
! { A, B, C, D, E, F, G, H }
1472 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I }
1473 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I, J }
1474 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I, J, K }
1475 fnptr_impls_args
! { A, B, C, D, E, F, G, H, I, J, K, L }
1477 /// Create a `const` raw pointer to a place, without creating an intermediate reference.
1479 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1480 /// and points to initialized data. For cases where those requirements do not hold,
1481 /// raw pointers should be used instead. However, `&expr as *const _` creates a reference
1482 /// before casting it to a raw pointer, and that reference is subject to the same rules
1483 /// as all other references. This macro can create a raw pointer *without* creating
1484 /// a reference first.
1489 /// #![feature(raw_ref_macros)]
1498 /// let packed = Packed { f1: 1, f2: 2 };
1499 /// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1500 /// let raw_f2 = ptr::raw_const!(packed.f2);
1501 /// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
1503 #[unstable(feature = "raw_ref_macros", issue = "73394")]
1504 #[rustc_macro_transparency = "semitransparent"]
1505 #[allow_internal_unstable(raw_ref_op)]
1506 pub macro raw_const($e
:expr
) {
1510 /// Create a `mut` raw pointer to a place, without creating an intermediate reference.
1512 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1513 /// and points to initialized data. For cases where those requirements do not hold,
1514 /// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
1515 /// before casting it to a raw pointer, and that reference is subject to the same rules
1516 /// as all other references. This macro can create a raw pointer *without* creating
1517 /// a reference first.
1522 /// #![feature(raw_ref_macros)]
1531 /// let mut packed = Packed { f1: 1, f2: 2 };
1532 /// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1533 /// let raw_f2 = ptr::raw_mut!(packed.f2);
1534 /// unsafe { raw_f2.write_unaligned(42); }
1535 /// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
1537 #[unstable(feature = "raw_ref_macros", issue = "73394")]
1538 #[rustc_macro_transparency = "semitransparent"]
1539 #[allow_internal_unstable(raw_ref_op)]
1540 pub macro raw_mut($e
:expr
) {