Skip to content

Commit 3b8a457

Browse files
authored
Rollup merge of rust-lang#39716 - F001:swapCell, r=alexcrichton
Add `swap` method for `Cell` Addition to rust-lang#39264 r? @alexcrichton
2 parents 956e2bc + a5e8bbf commit 3b8a457

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/libcore/cell.rs

+27
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ use fmt::{self, Debug, Display};
186186
use marker::Unsize;
187187
use mem;
188188
use ops::{Deref, DerefMut, CoerceUnsized};
189+
use ptr;
189190

190191
/// A mutable memory location.
191192
///
@@ -387,6 +388,32 @@ impl<T> Cell<T> {
387388
drop(old);
388389
}
389390

391+
/// Swaps the values of two Cells.
392+
/// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
393+
///
394+
/// # Examples
395+
///
396+
/// ```
397+
/// #![feature(move_cell)]
398+
/// use std::cell::Cell;
399+
///
400+
/// let c1 = Cell::new(5i32);
401+
/// let c2 = Cell::new(10i32);
402+
/// c1.swap(&c2);
403+
/// assert_eq!(10, c1.get());
404+
/// assert_eq!(5, c2.get());
405+
/// ```
406+
#[inline]
407+
#[unstable(feature = "move_cell", issue = "39264")]
408+
pub fn swap(&self, other: &Self) {
409+
if ptr::eq(self, other) {
410+
return;
411+
}
412+
unsafe {
413+
ptr::swap(self.value.get(), other.value.get());
414+
}
415+
}
416+
390417
/// Replaces the contained value.
391418
///
392419
/// # Examples

0 commit comments

Comments
 (0)