Skip to content

Commit 6c54745

Browse files
committed
Make pointer::with_metadata_of const (+simplify implementation)
1 parent 44fcfb0 commit 6c54745

File tree

2 files changed

+6
-20
lines changed

2 files changed

+6
-20
lines changed

library/core/src/ptr/const_ptr.rs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -79,19 +79,14 @@ impl<T: ?Sized> *const T {
7979
/// }
8080
/// ```
8181
#[unstable(feature = "set_ptr_value", issue = "75091")]
82+
#[rustc_const_unstable(feature = "set_ptr_value", issue = "75091")]
8283
#[must_use = "returns a new pointer rather than modifying its argument"]
8384
#[inline]
84-
pub fn with_metadata_of<U>(self, mut val: *const U) -> *const U
85+
pub const fn with_metadata_of<U>(self, meta: *const U) -> *const U
8586
where
8687
U: ?Sized,
8788
{
88-
let target = &mut val as *mut *const U as *mut *const u8;
89-
// SAFETY: In case of a thin pointer, this operations is identical
90-
// to a simple assignment. In case of a fat pointer, with the current
91-
// fat pointer layout implementation, the first field of such a
92-
// pointer is always the data pointer, which is likewise assigned.
93-
unsafe { *target = self as *const u8 };
94-
val
89+
from_raw_parts::<U>(self as *const (), metadata(meta))
9590
}
9691

9792
/// Changes constness without changing the type.

library/core/src/ptr/mut_ptr.rs

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -78,23 +78,14 @@ impl<T: ?Sized> *mut T {
7878
/// }
7979
/// ```
8080
#[unstable(feature = "set_ptr_value", issue = "75091")]
81+
#[rustc_const_unstable(feature = "set_ptr_value", issue = "75091")]
8182
#[must_use = "returns a new pointer rather than modifying its argument"]
8283
#[inline]
83-
pub fn with_metadata_of<U>(self, val: *const U) -> *mut U
84+
pub const fn with_metadata_of<U>(self, meta: *const U) -> *mut U
8485
where
8586
U: ?Sized,
8687
{
87-
// Prepare in the type system that we will replace the pointer value with a mutable
88-
// pointer, taking the mutable provenance from the `self` pointer.
89-
let mut val = val as *mut U;
90-
// Pointer to the pointer value within the value.
91-
let target = &mut val as *mut *mut U as *mut *mut u8;
92-
// SAFETY: In case of a thin pointer, this operations is identical
93-
// to a simple assignment. In case of a fat pointer, with the current
94-
// fat pointer layout implementation, the first field of such a
95-
// pointer is always the data pointer, which is likewise assigned.
96-
unsafe { *target = self as *mut u8 };
97-
val
88+
from_raw_parts_mut::<U>(self as *mut (), metadata(meta))
9889
}
9990

10091
/// Changes constness without changing the type.

0 commit comments

Comments
 (0)