Skip to content

Commit 4cc46df

Browse files
committed
Add replace and swap convenience methods to NonNull
1 parent 4bcdd3b commit 4cc46df

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Diff for: library/core/src/ptr/non_null.rs

+35
Original file line numberDiff line numberDiff line change
@@ -1187,6 +1187,41 @@ impl<T: ?Sized> NonNull<T> {
11871187
// SAFETY: the caller must uphold the safety contract for `write_unaligned`.
11881188
unsafe { ptr::write_unaligned(self.as_ptr(), val) }
11891189
}
1190+
1191+
/// Replaces the value at `self` with `src`, returning the old
1192+
/// value, without dropping either.
1193+
///
1194+
/// See [`ptr::replace`] for safety concerns and examples.
1195+
///
1196+
/// [`ptr::replace`]: crate::ptr::replace()
1197+
#[unstable(feature = "non_null_convenience", issue = "117691")]
1198+
#[inline(always)]
1199+
pub unsafe fn replace(self, src: T) -> T
1200+
where
1201+
T: Sized,
1202+
{
1203+
// SAFETY: the caller must uphold the safety contract for `replace`.
1204+
unsafe { ptr::replace(self.as_ptr(), src) }
1205+
}
1206+
1207+
/// Swaps the values at two mutable locations of the same type, without
1208+
/// deinitializing either. They may overlap, unlike `mem::swap` which is
1209+
/// otherwise equivalent.
1210+
///
1211+
/// See [`ptr::swap`] for safety concerns and examples.
1212+
///
1213+
/// [`ptr::swap`]: crate::ptr::swap()
1214+
#[unstable(feature = "non_null_convenience", issue = "117691")]
1215+
#[rustc_const_unstable(feature = "non_null_convenience", issue = "117691")]
1216+
//#[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1217+
#[inline(always)]
1218+
pub const unsafe fn swap(self, with: NonNull<T>)
1219+
where
1220+
T: Sized,
1221+
{
1222+
// SAFETY: the caller must uphold the safety contract for `swap`.
1223+
unsafe { ptr::swap(self.as_ptr(), with.as_ptr()) }
1224+
}
11901225
}
11911226

11921227
impl<T> NonNull<[T]> {

0 commit comments

Comments
 (0)