]> git.proxmox.com Git - rustc.git/blob - src/libcore/ptr/mod.rs
New upstream version 1.46.0+dfsg1
[rustc.git] / src / libcore / ptr / mod.rs
1 //! Manually manage memory through raw pointers.
2 //!
3 //! *[See also the pointer primitive types](../../std/primitive.pointer.html).*
4 //!
5 //! # Safety
6 //!
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.
14 //!
15 //! The precise rules for validity are not determined yet. The guarantees that are
16 //! provided at this point are very minimal:
17 //!
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
20 //! [size zero][zst].
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.
34 //!
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].
40 //!
41 //! ## Alignment
42 //!
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`].
49 //!
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.
53 //!
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
67
68 #![stable(feature = "rust1", since = "1.0.0")]
69
70 use crate::cmp::Ordering;
71 use crate::fmt;
72 use crate::hash;
73 use crate::intrinsics::{self, abort, is_aligned_and_not_null, is_nonoverlapping};
74 use crate::mem::{self, MaybeUninit};
75
76 #[stable(feature = "rust1", since = "1.0.0")]
77 #[doc(inline)]
78 pub use crate::intrinsics::copy_nonoverlapping;
79
80 #[stable(feature = "rust1", since = "1.0.0")]
81 #[doc(inline)]
82 pub use crate::intrinsics::copy;
83
84 #[stable(feature = "rust1", since = "1.0.0")]
85 #[doc(inline)]
86 pub use crate::intrinsics::write_bytes;
87
88 mod non_null;
89 #[stable(feature = "nonnull", since = "1.25.0")]
90 pub use non_null::NonNull;
91
92 mod unique;
93 #[unstable(feature = "ptr_internals", issue = "none")]
94 pub use unique::Unique;
95
96 mod const_ptr;
97 mod mut_ptr;
98
99 /// Executes the destructor (if any) of the pointed-to value.
100 ///
101 /// This is semantically equivalent to calling [`ptr::read`] and discarding
102 /// the result, but has the following advantages:
103 ///
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.
107 ///
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
111 /// copy.
112 ///
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).
115 ///
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.
120 ///
121 /// [`ptr::read`]: ../ptr/fn.read.html
122 /// [`ptr::read_unaligned`]: ../ptr/fn.read_unaligned.html
123 /// [pinned]: ../pin/index.html
124 ///
125 /// # Safety
126 ///
127 /// Behavior is undefined if any of the following conditions are violated:
128 ///
129 /// * `to_drop` must be [valid] for both reads and writes.
130 ///
131 /// * `to_drop` must be properly aligned.
132 ///
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.
135 ///
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
140 /// dropped.
141 ///
142 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
143 ///
144 /// [valid]: ../ptr/index.html#safety
145 /// [`Copy`]: ../marker/trait.Copy.html
146 /// [`write`]: ../ptr/fn.write.html
147 ///
148 /// # Examples
149 ///
150 /// Manually remove the last item from a vector:
151 ///
152 /// ```
153 /// use std::ptr;
154 /// use std::rc::Rc;
155 ///
156 /// let last = Rc::new(1);
157 /// let weak = Rc::downgrade(&last);
158 ///
159 /// let mut v = vec![Rc::new(0), last];
160 ///
161 /// unsafe {
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.
166 /// v.set_len(1);
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);
170 /// }
171 ///
172 /// assert_eq!(v, &[0.into()]);
173 ///
174 /// // Ensure that the last item was dropped.
175 /// assert!(weak.upgrade().is_none());
176 /// ```
177 ///
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`
180 /// manually.
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.
187
188 // SAFETY: see comment above
189 unsafe { drop_in_place(to_drop) }
190 }
191
192 /// Creates a null raw pointer.
193 ///
194 /// # Examples
195 ///
196 /// ```
197 /// use std::ptr;
198 ///
199 /// let p: *const i32 = ptr::null();
200 /// assert!(p.is_null());
201 /// ```
202 #[inline(always)]
203 #[stable(feature = "rust1", since = "1.0.0")]
204 #[rustc_promotable]
205 #[rustc_const_stable(feature = "const_ptr_null", since = "1.32.0")]
206 pub const fn null<T>() -> *const T {
207 0 as *const T
208 }
209
210 /// Creates a null mutable raw pointer.
211 ///
212 /// # Examples
213 ///
214 /// ```
215 /// use std::ptr;
216 ///
217 /// let p: *mut i32 = ptr::null_mut();
218 /// assert!(p.is_null());
219 /// ```
220 #[inline(always)]
221 #[stable(feature = "rust1", since = "1.0.0")]
222 #[rustc_promotable]
223 #[rustc_const_stable(feature = "const_ptr_null", since = "1.32.0")]
224 pub const fn null_mut<T>() -> *mut T {
225 0 as *mut T
226 }
227
228 #[repr(C)]
229 pub(crate) union Repr<T> {
230 pub(crate) rust: *const [T],
231 rust_mut: *mut [T],
232 pub(crate) raw: FatPtr<T>,
233 }
234
235 #[repr(C)]
236 pub(crate) struct FatPtr<T> {
237 data: *const T,
238 pub(crate) len: usize,
239 }
240
241 /// Forms a raw slice from a pointer and a length.
242 ///
243 /// The `len` argument is the number of **elements**, not the number of bytes.
244 ///
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.
247 ///
248 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
249 ///
250 /// # Examples
251 ///
252 /// ```rust
253 /// use std::ptr;
254 ///
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);
260 /// ```
261 #[inline]
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
267 // guarantee.
268 unsafe { Repr { raw: FatPtr { data, len } }.rust }
269 }
270
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.
273 ///
274 /// See the documentation of [`slice_from_raw_parts`] for more details.
275 ///
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.
278 ///
279 /// [`slice_from_raw_parts`]: fn.slice_from_raw_parts.html
280 /// [`from_raw_parts_mut`]: ../../std/slice/fn.from_raw_parts_mut.html
281 ///
282 /// # Examples
283 ///
284 /// ```rust
285 /// use std::ptr;
286 ///
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);
290 ///
291 /// unsafe {
292 /// (*slice)[2] = 99; // assign a value at an index in the slice
293 /// };
294 ///
295 /// assert_eq!(unsafe { &*slice }[2], 99);
296 /// ```
297 #[inline]
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 }
304 }
305
306 /// Swaps the values at two mutable locations of the same type, without
307 /// deinitializing either.
308 ///
309 /// But for the following two exceptions, this function is semantically
310 /// equivalent to [`mem::swap`]:
311 ///
312 /// * It operates on raw pointers instead of references. When references are
313 /// available, [`mem::swap`] should be preferred.
314 ///
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.
318 ///
319 /// [`mem::swap`]: ../mem/fn.swap.html
320 ///
321 /// # Safety
322 ///
323 /// Behavior is undefined if any of the following conditions are violated:
324 ///
325 /// * Both `x` and `y` must be [valid] for both reads and writes.
326 ///
327 /// * Both `x` and `y` must be properly aligned.
328 ///
329 /// Note that even if `T` has size `0`, the pointers must be non-NULL and properly aligned.
330 ///
331 /// [valid]: ../ptr/index.html#safety
332 ///
333 /// # Examples
334 ///
335 /// Swapping two non-overlapping regions:
336 ///
337 /// ```
338 /// use std::ptr;
339 ///
340 /// let mut array = [0, 1, 2, 3];
341 ///
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]`
344 ///
345 /// unsafe {
346 /// ptr::swap(x, y);
347 /// assert_eq!([2, 3, 0, 1], array);
348 /// }
349 /// ```
350 ///
351 /// Swapping two overlapping regions:
352 ///
353 /// ```
354 /// use std::ptr;
355 ///
356 /// let mut array = [0, 1, 2, 3];
357 ///
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]`
360 ///
361 /// unsafe {
362 /// ptr::swap(x, y);
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);
369 /// }
370 /// ```
371 #[inline]
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();
377
378 // Perform the swap
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.
383 unsafe {
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);
387 }
388 }
389
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.
392 ///
393 /// # Safety
394 ///
395 /// Behavior is undefined if any of the following conditions are violated:
396 ///
397 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
398 /// size_of::<T>()` bytes.
399 ///
400 /// * Both `x` and `y` must be properly aligned.
401 ///
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.
405 ///
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.
408 ///
409 /// [valid]: ../ptr/index.html#safety
410 ///
411 /// # Examples
412 ///
413 /// Basic usage:
414 ///
415 /// ```
416 /// use std::ptr;
417 ///
418 /// let mut x = [1, 2, 3, 4];
419 /// let mut y = [7, 8, 9];
420 ///
421 /// unsafe {
422 /// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
423 /// }
424 ///
425 /// assert_eq!(x, [7, 8, 3, 4]);
426 /// assert_eq!(y, [1, 2, 9]);
427 /// ```
428 #[inline]
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))
435 {
436 // Not panicking to keep codegen impact smaller.
437 abort();
438 }
439
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) }
446 }
447
448 #[inline]
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.
455 unsafe {
456 let z = read(x);
457 copy_nonoverlapping(y, x, 1);
458 write(y, z);
459 }
460 } else {
461 // SAFETY: the caller must uphold the safety contract for `swap_nonoverlapping`.
462 unsafe { swap_nonoverlapping(x, y, 1) };
463 }
464 }
465
466 #[inline]
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.
472 //
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);
477
478 let block_size = mem::size_of::<Block>();
479
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
483 let mut i = 0;
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;
489
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`.
493 //
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`.
496 unsafe {
497 let x = x.add(i);
498 let y = y.add(i);
499
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);
505 }
506 i += block_size;
507 }
508
509 if i < len {
510 // Swap any remaining bytes
511 let mut t = mem::MaybeUninit::<UnalignedBlock>::uninit();
512 let rem = len - i;
513
514 let t = t.as_mut_ptr() as *mut u8;
515
516 // SAFETY: see previous safety comment.
517 unsafe {
518 let x = x.add(i);
519 let y = y.add(i);
520
521 copy_nonoverlapping(x, t, rem);
522 copy_nonoverlapping(y, x, rem);
523 copy_nonoverlapping(t, y, rem);
524 }
525 }
526 }
527
528 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
529 ///
530 /// Neither value is dropped.
531 ///
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.
535 ///
536 /// [`mem::replace`]: ../mem/fn.replace.html
537 ///
538 /// # Safety
539 ///
540 /// Behavior is undefined if any of the following conditions are violated:
541 ///
542 /// * `dst` must be [valid] for both reads and writes.
543 ///
544 /// * `dst` must be properly aligned.
545 ///
546 /// * `dst` must point to a properly initialized value of type `T`.
547 ///
548 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
549 ///
550 /// [valid]: ../ptr/index.html#safety
551 ///
552 /// # Examples
553 ///
554 /// ```
555 /// use std::ptr;
556 ///
557 /// let mut rust = vec!['b', 'u', 's', 't'];
558 ///
559 /// // `mem::replace` would have the same effect without requiring the unsafe
560 /// // block.
561 /// let b = unsafe {
562 /// ptr::replace(&mut rust[0], 'r')
563 /// };
564 ///
565 /// assert_eq!(b, 'b');
566 /// assert_eq!(rust, &['r', 'u', 's', 't']);
567 /// ```
568 #[inline]
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
574 // allocated object.
575 unsafe {
576 mem::swap(&mut *dst, &mut src); // cannot overlap
577 }
578 src
579 }
580
581 /// Reads the value from `src` without moving it. This leaves the
582 /// memory in `src` unchanged.
583 ///
584 /// # Safety
585 ///
586 /// Behavior is undefined if any of the following conditions are violated:
587 ///
588 /// * `src` must be [valid] for reads.
589 ///
590 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
591 /// case.
592 ///
593 /// * `src` must point to a properly initialized value of type `T`.
594 ///
595 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
596 ///
597 /// # Examples
598 ///
599 /// Basic usage:
600 ///
601 /// ```
602 /// let x = 12;
603 /// let y = &x as *const i32;
604 ///
605 /// unsafe {
606 /// assert_eq!(std::ptr::read(y), 12);
607 /// }
608 /// ```
609 ///
610 /// Manually implement [`mem::swap`]:
611 ///
612 /// ```
613 /// use std::ptr;
614 ///
615 /// fn swap<T>(a: &mut T, b: &mut T) {
616 /// unsafe {
617 /// // Create a bitwise copy of the value at `a` in `tmp`.
618 /// let tmp = ptr::read(a);
619 ///
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`.
624 ///
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);
628 ///
629 /// // As above, exiting here could trigger undefined behavior because
630 /// // the same value is referenced by `a` and `b`.
631 ///
632 /// // Move `tmp` into `b`.
633 /// ptr::write(b, tmp);
634 ///
635 /// // `tmp` has been moved (`write` takes ownership of its second argument),
636 /// // so nothing is dropped implicitly here.
637 /// }
638 /// }
639 ///
640 /// let mut foo = "foo".to_owned();
641 /// let mut bar = "bar".to_owned();
642 ///
643 /// swap(&mut foo, &mut bar);
644 ///
645 /// assert_eq!(foo, "bar");
646 /// assert_eq!(bar, "foo");
647 /// ```
648 ///
649 /// ## Ownership of the Returned Value
650 ///
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`.
655 ///
656 /// [`write`] can be used to overwrite data without causing it to be dropped.
657 ///
658 /// ```
659 /// use std::ptr;
660 ///
661 /// let mut s = String::from("foo");
662 /// unsafe {
663 /// // `s2` now points to the same underlying memory as `s`.
664 /// let mut s2: String = ptr::read(&s);
665 ///
666 /// assert_eq!(s2, "foo");
667 ///
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
670 /// // been freed.
671 /// s2 = String::default();
672 /// assert_eq!(s2, "");
673 ///
674 /// // Assigning to `s` would cause the old value to be dropped again,
675 /// // resulting in undefined behavior.
676 /// // s = String::from("bar"); // ERROR
677 ///
678 /// // `ptr::write` can be used to overwrite a value without dropping it.
679 /// ptr::write(&mut s, String::from("bar"));
680 /// }
681 ///
682 /// assert_eq!(s, "bar");
683 /// ```
684 ///
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
690 #[inline]
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.
698 //
699 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
700 // to be properly initialized.
701 unsafe {
702 copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
703 tmp.assume_init()
704 }
705 }
706
707 /// Reads the value from `src` without moving it. This leaves the
708 /// memory in `src` unchanged.
709 ///
710 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
711 ///
712 /// # Safety
713 ///
714 /// Behavior is undefined if any of the following conditions are violated:
715 ///
716 /// * `src` must be [valid] for reads.
717 ///
718 /// * `src` must point to a properly initialized value of type `T`.
719 ///
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].
723 ///
724 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
725 ///
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
731 ///
732 /// ## On `packed` structs
733 ///
734 /// It is currently impossible to create raw pointers to unaligned fields
735 /// of a packed struct.
736 ///
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.
744 ///
745 /// An example of what not to do and how this relates to `read_unaligned` is:
746 ///
747 /// ```no_run
748 /// #[repr(packed, C)]
749 /// struct Packed {
750 /// _padding: u8,
751 /// unaligned: u32,
752 /// }
753 ///
754 /// let packed = Packed {
755 /// _padding: 0x00,
756 /// unaligned: 0x01020304,
757 /// };
758 ///
759 /// let v = unsafe {
760 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
761 /// let unaligned =
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.
766 /// as *const u32;
767 ///
768 /// let v = std::ptr::read_unaligned(unaligned);
769 ///
770 /// v
771 /// };
772 /// ```
773 ///
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.
776 ///
777 /// # Examples
778 ///
779 /// Read an usize value from a byte buffer:
780 ///
781 /// ```
782 /// use std::mem;
783 ///
784 /// fn read_usize(x: &[u8]) -> usize {
785 /// assert!(x.len() >= mem::size_of::<usize>());
786 ///
787 /// let ptr = x.as_ptr() as *const usize;
788 ///
789 /// unsafe { ptr.read_unaligned() }
790 /// }
791 /// ```
792 #[inline]
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.
800 //
801 // Also, since we just wrote a valid value into `tmp`, it is guaranteed
802 // to be properly initialized.
803 unsafe {
804 copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::<T>());
805 tmp.assume_init()
806 }
807 }
808
809 /// Overwrites a memory location with the given value without reading or
810 /// dropping the old value.
811 ///
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.
815 ///
816 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
817 /// location pointed to by `dst`.
818 ///
819 /// This is appropriate for initializing uninitialized memory, or overwriting
820 /// memory that has previously been [`read`] from.
821 ///
822 /// [`read`]: ./fn.read.html
823 ///
824 /// # Safety
825 ///
826 /// Behavior is undefined if any of the following conditions are violated:
827 ///
828 /// * `dst` must be [valid] for writes.
829 ///
830 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
831 /// case.
832 ///
833 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
834 ///
835 /// [valid]: ../ptr/index.html#safety
836 /// [`write_unaligned`]: ./fn.write_unaligned.html
837 ///
838 /// # Examples
839 ///
840 /// Basic usage:
841 ///
842 /// ```
843 /// let mut x = 0;
844 /// let y = &mut x as *mut i32;
845 /// let z = 12;
846 ///
847 /// unsafe {
848 /// std::ptr::write(y, z);
849 /// assert_eq!(std::ptr::read(y), 12);
850 /// }
851 /// ```
852 ///
853 /// Manually implement [`mem::swap`]:
854 ///
855 /// ```
856 /// use std::ptr;
857 ///
858 /// fn swap<T>(a: &mut T, b: &mut T) {
859 /// unsafe {
860 /// // Create a bitwise copy of the value at `a` in `tmp`.
861 /// let tmp = ptr::read(a);
862 ///
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`.
867 ///
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);
871 ///
872 /// // As above, exiting here could trigger undefined behavior because
873 /// // the same value is referenced by `a` and `b`.
874 ///
875 /// // Move `tmp` into `b`.
876 /// ptr::write(b, tmp);
877 ///
878 /// // `tmp` has been moved (`write` takes ownership of its second argument),
879 /// // so nothing is dropped implicitly here.
880 /// }
881 /// }
882 ///
883 /// let mut foo = "foo".to_owned();
884 /// let mut bar = "bar".to_owned();
885 ///
886 /// swap(&mut foo, &mut bar);
887 ///
888 /// assert_eq!(foo, "bar");
889 /// assert_eq!(bar, "foo");
890 /// ```
891 ///
892 /// [`mem::swap`]: ../mem/fn.swap.html
893 #[inline]
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.
898 abort();
899 }
900 // SAFETY: the caller must uphold the safety contract for `move_val_init`.
901 unsafe { intrinsics::move_val_init(&mut *dst, src) }
902 }
903
904 /// Overwrites a memory location with the given value without reading or
905 /// dropping the old value.
906 ///
907 /// Unlike [`write`], the pointer may be unaligned.
908 ///
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.
912 ///
913 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
914 /// location pointed to by `dst`.
915 ///
916 /// This is appropriate for initializing uninitialized memory, or overwriting
917 /// memory that has previously been read with [`read_unaligned`].
918 ///
919 /// [`write`]: ./fn.write.html
920 /// [`read_unaligned`]: ./fn.read_unaligned.html
921 ///
922 /// # Safety
923 ///
924 /// Behavior is undefined if any of the following conditions are violated:
925 ///
926 /// * `dst` must be [valid] for writes.
927 ///
928 /// Note that even if `T` has size `0`, the pointer must be non-NULL.
929 ///
930 /// [valid]: ../ptr/index.html#safety
931 ///
932 /// ## On `packed` structs
933 ///
934 /// It is currently impossible to create raw pointers to unaligned fields
935 /// of a packed struct.
936 ///
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.
944 ///
945 /// An example of what not to do and how this relates to `write_unaligned` is:
946 ///
947 /// ```no_run
948 /// #[repr(packed, C)]
949 /// struct Packed {
950 /// _padding: u8,
951 /// unaligned: u32,
952 /// }
953 ///
954 /// let v = 0x01020304;
955 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
956 ///
957 /// let v = unsafe {
958 /// // Here we attempt to take the address of a 32-bit integer which is not aligned.
959 /// let unaligned =
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.
964 /// as *mut u32;
965 ///
966 /// std::ptr::write_unaligned(unaligned, v);
967 ///
968 /// v
969 /// };
970 /// ```
971 ///
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.
974 ///
975 /// # Examples
976 ///
977 /// Write an usize value to a byte buffer:
978 ///
979 /// ```
980 /// use std::mem;
981 ///
982 /// fn write_usize(x: &mut [u8], val: usize) {
983 /// assert!(x.len() >= mem::size_of::<usize>());
984 ///
985 /// let ptr = x.as_mut_ptr() as *mut usize;
986 ///
987 /// unsafe { ptr.write_unaligned(val) }
988 /// }
989 /// ```
990 #[inline]
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.
996 unsafe {
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>());
999 }
1000 mem::forget(src);
1001 }
1002
1003 /// Performs a volatile read of the value from `src` without moving it. This
1004 /// leaves the memory in `src` unchanged.
1005 ///
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
1008 /// operations.
1009 ///
1010 /// [`write_volatile`]: ./fn.write_volatile.html
1011 ///
1012 /// # Notes
1013 ///
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].
1018 ///
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.
1023 ///
1024 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1025 ///
1026 /// # Safety
1027 ///
1028 /// Behavior is undefined if any of the following conditions are violated:
1029 ///
1030 /// * `src` must be [valid] for reads.
1031 ///
1032 /// * `src` must be properly aligned.
1033 ///
1034 /// * `src` must point to a properly initialized value of type `T`.
1035 ///
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
1040 /// incorrect.
1041 ///
1042 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
1043 ///
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
1048 ///
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.
1054 ///
1055 /// # Examples
1056 ///
1057 /// Basic usage:
1058 ///
1059 /// ```
1060 /// let x = 12;
1061 /// let y = &x as *const i32;
1062 ///
1063 /// unsafe {
1064 /// assert_eq!(std::ptr::read_volatile(y), 12);
1065 /// }
1066 /// ```
1067 #[inline]
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.
1072 abort();
1073 }
1074 // SAFETY: the caller must uphold the safety contract for `volatile_load`.
1075 unsafe { intrinsics::volatile_load(src) }
1076 }
1077
1078 /// Performs a volatile write of a memory location with the given value without
1079 /// reading or dropping the old value.
1080 ///
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
1083 /// operations.
1084 ///
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.
1088 ///
1089 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1090 /// location pointed to by `dst`.
1091 ///
1092 /// [`read_volatile`]: ./fn.read_volatile.html
1093 ///
1094 /// # Notes
1095 ///
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].
1100 ///
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.
1105 ///
1106 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1107 ///
1108 /// # Safety
1109 ///
1110 /// Behavior is undefined if any of the following conditions are violated:
1111 ///
1112 /// * `dst` must be [valid] for writes.
1113 ///
1114 /// * `dst` must be properly aligned.
1115 ///
1116 /// Note that even if `T` has size `0`, the pointer must be non-NULL and properly aligned.
1117 ///
1118 /// [valid]: ../ptr/index.html#safety
1119 ///
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.
1125 ///
1126 /// # Examples
1127 ///
1128 /// Basic usage:
1129 ///
1130 /// ```
1131 /// let mut x = 0;
1132 /// let y = &mut x as *mut i32;
1133 /// let z = 12;
1134 ///
1135 /// unsafe {
1136 /// std::ptr::write_volatile(y, z);
1137 /// assert_eq!(std::ptr::read_volatile(y), 12);
1138 /// }
1139 /// ```
1140 #[inline]
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.
1145 abort();
1146 }
1147 // SAFETY: the caller must uphold the safety contract for `volatile_store`.
1148 unsafe {
1149 intrinsics::volatile_store(dst, src);
1150 }
1151 }
1152
1153 /// Align pointer `p`.
1154 ///
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`.
1157 ///
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
1160 /// constants.
1161 ///
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.
1165 ///
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`.
1170 ///
1171 /// This implementation is tailored for align_offset and has following preconditions:
1172 ///
1173 /// * `m` is a power-of-two;
1174 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1175 ///
1176 /// Implementation of this function shall not panic. Ever.
1177 #[inline]
1178 fn mod_inv(x: usize, m: usize) -> usize {
1179 /// Multiplicative modular inverse table modulo 2⁴ = 16.
1180 ///
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;
1186 /// INV_TABLE_MOD²
1187 const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
1188
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)
1192 } else {
1193 // We iterate "up" using the following formula:
1194 //
1195 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1196 //
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;
1200 loop {
1201 // y = y * (2 - xy) mod n
1202 //
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
1206 // anyway.
1207 inverse = inverse.wrapping_mul(2usize.wrapping_sub(x.wrapping_mul(inverse)));
1208 if going_mod >= m {
1209 return inverse & (m - 1);
1210 }
1211 going_mod = going_mod.wrapping_mul(going_mod);
1212 }
1213 }
1214 }
1215
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;
1219
1220 if pmoda == 0 {
1221 // Already aligned. Yay!
1222 return 0;
1223 }
1224
1225 if stride <= 1 {
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.
1229 !0
1230 } else {
1231 a.wrapping_sub(pmoda)
1232 };
1233 }
1234
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;
1239
1240 if p as usize & (gcd.wrapping_sub(1)) == 0 {
1241 // This branch solves for the following linear congruence equation:
1242 //
1243 // ` p + so = 0 mod a `
1244 //
1245 // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1246 // requested alignment.
1247 //
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:
1250 //
1251 // ` p' + s'o = 0 mod a' `
1252 // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1253 //
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
1256 // divided by `g`).
1257 // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1258 // co-prime.
1259 //
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;
1267 }
1268
1269 // Cannot be aligned at all.
1270 usize::MAX
1271 }
1272
1273 /// Compares raw pointers for equality.
1274 ///
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`.
1278 ///
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).
1282 ///
1283 /// # Examples
1284 ///
1285 /// ```
1286 /// use std::ptr;
1287 ///
1288 /// let five = 5;
1289 /// let other_five = 5;
1290 /// let five_ref = &five;
1291 /// let same_five_ref = &five;
1292 /// let other_five_ref = &other_five;
1293 ///
1294 /// assert!(five_ref == same_five_ref);
1295 /// assert!(ptr::eq(five_ref, same_five_ref));
1296 ///
1297 /// assert!(five_ref == other_five_ref);
1298 /// assert!(!ptr::eq(five_ref, other_five_ref));
1299 /// ```
1300 ///
1301 /// Slices are also compared by their length (fat pointers):
1302 ///
1303 /// ```
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]));
1308 /// ```
1309 ///
1310 /// Traits are also compared by their implementation:
1311 ///
1312 /// ```
1313 /// #[repr(transparent)]
1314 /// struct Wrapper { member: i32 }
1315 ///
1316 /// trait Trait {}
1317 /// impl Trait for Wrapper {}
1318 /// impl Trait for i32 {}
1319 ///
1320 /// let wrapper = Wrapper { member: 10 };
1321 ///
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
1326 /// ));
1327 ///
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,
1332 /// ));
1333 /// assert!(!std::ptr::eq(
1334 /// &wrapper as &dyn Trait as *const dyn Trait,
1335 /// &wrapper.member as &dyn Trait as *const dyn Trait,
1336 /// ));
1337 ///
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,
1342 /// ));
1343 /// ```
1344 #[stable(feature = "ptr_eq", since = "1.17.0")]
1345 #[inline]
1346 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
1347 a == b
1348 }
1349
1350 /// Hash a raw pointer.
1351 ///
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).
1355 ///
1356 /// # Examples
1357 ///
1358 /// ```
1359 /// use std::collections::hash_map::DefaultHasher;
1360 /// use std::hash::{Hash, Hasher};
1361 /// use std::ptr;
1362 ///
1363 /// let five = 5;
1364 /// let five_ref = &five;
1365 ///
1366 /// let mut hasher = DefaultHasher::new();
1367 /// ptr::hash(five_ref, &mut hasher);
1368 /// let actual = hasher.finish();
1369 ///
1370 /// let mut hasher = DefaultHasher::new();
1371 /// (five_ref as *const i32).hash(&mut hasher);
1372 /// let expected = hasher.finish();
1373 ///
1374 /// assert_eq!(actual, expected);
1375 /// ```
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;
1379 hashee.hash(into);
1380 }
1381
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 {
1387 #[inline]
1388 fn eq(&self, other: &Self) -> bool {
1389 *self as usize == *other as usize
1390 }
1391 }
1392
1393 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1394 impl<Ret, $($Arg),*> Eq for $FnTy {}
1395
1396 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1397 impl<Ret, $($Arg),*> PartialOrd for $FnTy {
1398 #[inline]
1399 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1400 (*self as usize).partial_cmp(&(*other as usize))
1401 }
1402 }
1403
1404 #[stable(feature = "fnptr_impls", since = "1.4.0")]
1405 impl<Ret, $($Arg),*> Ord for $FnTy {
1406 #[inline]
1407 fn cmp(&self, other: &Self) -> Ordering {
1408 (*self as usize).cmp(&(*other as usize))
1409 }
1410 }
1411
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)
1416 }
1417 }
1418
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.
1425 //
1426 // https://github.com/avr-rust/rust/issues/143
1427 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1428 }
1429 }
1430
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.
1437 //
1438 // https://github.com/avr-rust/rust/issues/143
1439 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1440 }
1441 }
1442 }
1443 }
1444
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),+ }
1453 };
1454 () => {
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, }
1460 };
1461 }
1462
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 }
1476
1477 /// Create a `const` raw pointer to a place, without creating an intermediate reference.
1478 ///
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.
1485 ///
1486 /// # Example
1487 ///
1488 /// ```
1489 /// #![feature(raw_ref_macros)]
1490 /// use std::ptr;
1491 ///
1492 /// #[repr(packed)]
1493 /// struct Packed {
1494 /// f1: u8,
1495 /// f2: u16,
1496 /// }
1497 ///
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);
1502 /// ```
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) {
1507 &raw const $e
1508 }
1509
1510 /// Create a `mut` raw pointer to a place, without creating an intermediate reference.
1511 ///
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.
1518 ///
1519 /// # Example
1520 ///
1521 /// ```
1522 /// #![feature(raw_ref_macros)]
1523 /// use std::ptr;
1524 ///
1525 /// #[repr(packed)]
1526 /// struct Packed {
1527 /// f1: u8,
1528 /// f2: u16,
1529 /// }
1530 ///
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.
1536 /// ```
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) {
1541 &raw mut $e
1542 }