Skip to content

Commit ba65645

Browse files
committed
Auto merge of #44031 - scottmcm:swap_with_slice, r=alexcrichton
Add [T]::swap_with_slice The safe version of a method from `ptr`, like `[T]::copy_from_slice` is. Tracking issue: #44030
2 parents 32b50e2 + c4cb2d1 commit ba65645

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

src/liballoc/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@
121121
#![feature(unsize)]
122122
#![feature(allocator_internals)]
123123

124-
#![cfg_attr(not(test), feature(fused, fn_traits, placement_new_protocol))]
124+
#![cfg_attr(not(test), feature(fused, fn_traits, placement_new_protocol, swap_with_slice))]
125125
#![cfg_attr(test, feature(test, box_heap))]
126126

127127
// Allow testing this library

src/liballoc/slice.rs

+25
Original file line numberDiff line numberDiff line change
@@ -1461,6 +1461,31 @@ impl<T> [T] {
14611461
core_slice::SliceExt::copy_from_slice(self, src)
14621462
}
14631463

1464+
/// Swaps all elements in `self` with those in `src`.
1465+
///
1466+
/// The length of `src` must be the same as `self`.
1467+
///
1468+
/// # Panics
1469+
///
1470+
/// This function will panic if the two slices have different lengths.
1471+
///
1472+
/// # Example
1473+
///
1474+
/// ```
1475+
/// #![feature(swap_with_slice)]
1476+
///
1477+
/// let mut src = [1, 2, 3];
1478+
/// let mut dst = [7, 8, 9];
1479+
///
1480+
/// src.swap_with_slice(&mut dst);
1481+
/// assert_eq!(src, [7, 8, 9]);
1482+
/// assert_eq!(dst, [1, 2, 3]);
1483+
/// ```
1484+
#[unstable(feature = "swap_with_slice", issue = "44030")]
1485+
pub fn swap_with_slice(&mut self, src: &mut [T]) {
1486+
core_slice::SliceExt::swap_with_slice(self, src)
1487+
}
1488+
14641489
/// Copies `self` into a new `Vec`.
14651490
///
14661491
/// # Examples

src/libcore/slice/mod.rs

+13
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,9 @@ pub trait SliceExt {
212212
#[stable(feature = "copy_from_slice", since = "1.9.0")]
213213
fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
214214

215+
#[unstable(feature = "swap_with_slice", issue = "44030")]
216+
fn swap_with_slice(&mut self, src: &mut [Self::Item]);
217+
215218
#[stable(feature = "sort_unstable", since = "1.20.0")]
216219
fn sort_unstable(&mut self)
217220
where Self::Item: Ord;
@@ -673,6 +676,16 @@ impl<T> SliceExt for [T] {
673676
}
674677
}
675678

679+
#[inline]
680+
fn swap_with_slice(&mut self, src: &mut [T]) {
681+
assert!(self.len() == src.len(),
682+
"destination and source slices have different lengths");
683+
unsafe {
684+
ptr::swap_nonoverlapping(
685+
self.as_mut_ptr(), src.as_mut_ptr(), self.len());
686+
}
687+
}
688+
676689
#[inline]
677690
fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, mut f: F) -> Result<usize, usize>
678691
where F: FnMut(&'a Self::Item) -> B,

0 commit comments

Comments
 (0)