Skip to content

Commit c2adb49

Browse files
committed
try_cast_aligned: avoid bare int-to-ptr casts
1 parent 6eef33b commit c2adb49

File tree

3 files changed

+10
-7
lines changed

3 files changed

+10
-7
lines changed

library/core/src/ptr/const_ptr.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,14 @@ impl<T: ?Sized> *const T {
7575
///
7676
/// ```rust
7777
/// #![feature(pointer_try_cast_aligned)]
78+
/// use std::ptr;
7879
///
79-
/// let aligned: *const u8 = 0x1000 as _;
80+
/// let aligned: *const u8 = ptr::without_provenance(0x1000);
8081
///
8182
/// // i32 has at most 4-byte alignment, so this will succeed
8283
/// assert!(aligned.try_cast_aligned::<i32>().is_some());
8384
///
84-
/// let unaligned: *const u8 = 0x1001 as _;
85+
/// let unaligned: *const u8 = ptr::without_provenance(0x1001);
8586
///
8687
/// // i32 has at least 2-byte alignment, so this will fail
8788
/// assert!(unaligned.try_cast_aligned::<i32>().is_none());

library/core/src/ptr/mut_ptr.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,14 @@ impl<T: ?Sized> *mut T {
5757
///
5858
/// ```rust
5959
/// #![feature(pointer_try_cast_aligned)]
60+
/// use std::ptr;
6061
///
61-
/// let aligned: *mut u8 = 0x1000 as _;
62+
/// let aligned: *mut u8 = ptr::without_provenance_mut(0x1000);
6263
///
6364
/// // i32 has at most 4-byte alignment, so this will succeed
6465
/// assert!(aligned.try_cast_aligned::<i32>().is_some());
6566
///
66-
/// let unaligned: *mut u8 = 0x1001 as _;
67+
/// let unaligned: *mut u8 = ptr::without_provenance_mut(0x1001);
6768
///
6869
/// // i32 has at least 2-byte alignment, so this will fail
6970
/// assert!(unaligned.try_cast_aligned::<i32>().is_none());

library/core/src/ptr/non_null.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -498,15 +498,16 @@ impl<T: ?Sized> NonNull<T> {
498498
/// # Examples
499499
///
500500
/// ```rust
501-
/// #![feature(pointer_try_cast_aligned)]
501+
/// #![feature(pointer_try_cast_aligned, nonnull_provenance)]
502+
/// use std::num::NonZero;
502503
/// use std::ptr::NonNull;
503504
///
504-
/// let aligned: NonNull<u8> = NonNull::new(0x1000 as _).unwrap();
505+
/// let aligned: NonNull<u8> = NonNull::without_provenance(NonZero::new(0x1000).unwrap());
505506
///
506507
/// // i32 has at most 4-byte alignment, so this will succeed
507508
/// assert!(aligned.try_cast_aligned::<i32>().is_some());
508509
///
509-
/// let unaligned: NonNull<u8> = NonNull::new(0x1001 as _).unwrap();
510+
/// let unaligned: NonNull<u8> = NonNull::without_provenance(NonZero::new(0x1001).unwrap());
510511
///
511512
/// // i32 has at least 2-byte alignment, so this will fail
512513
/// assert!(unaligned.try_cast_aligned::<i32>().is_none());

0 commit comments

Comments
 (0)