1 use core::cell::UnsafeCell; 2 use core::mem; 3 4 /// A move cell. 5 /// 6 /// This allows you to take ownership and replace the internal data with a new value. The 7 /// functionality is similar to the one provided by [RFC #1659](https://github.com/rust-lang/rfcs/pull/1659). 8 // TODO use that rfc ^ 9 pub struct MoveCell<T> { 10 /// The inner data. 11 inner: UnsafeCell<T>, 12 } 13 14 impl<T> MoveCell<T> { 15 /// Create a new cell with some inner data. 16 #[inline] 17 pub const fn new(data: T) -> MoveCell<T> { 18 MoveCell { 19 inner: UnsafeCell::new(data), 20 } 21 } 22 23 /// Replace the inner data and return the old. 24 #[inline] 25 pub fn replace(&self, new: T) -> T { 26 mem::replace(unsafe { &mut *self.inner.get() }, new) 27 } 28 } 29 30 #[cfg(test)] 31 mod test { 32 use super::*; 33 34 #[test] 35 fn test_cell() { 36 let cell = MoveCell::new(200); 37 assert_eq!(cell.replace(300), 200); 38 assert_eq!(cell.replace(4), 300); 39 } 40 } 41