Any way to safely swap Cell<T> with T?

It seems to me like it should be completely safe to swap a T with a Cell<T> - but there is only Cell::swap that swaps 2 Cells or of course std::mem::swap that swaps 2 of anything of the same type. I could write something to swap T with Cell<T> using unsafe, but am wondering if there is a reason I'm not thinking of that would explain why it doesn't already exist. It seems like it would be useful. Note that Cell::replace isn't what I'm after, because that requires ownership of the T value instead of a &mut T.

See from_mut.

fn example<T>(cell: &Cell<T>, other: &mut T) {
    cell.swap(Cell::from_mut(other));
}
13 Likes

Of course.

But not obviously so. Only after thinking through how Cell::from_mut must work - it takes a &mut T, so cannot acquire ownership, which means that the resulting cell must be around the original T - the addresses would match. I had quickly dismissed the possibility based on the presumption that the two cells would be involved in the swap without impacting the original other value. I didn't even bother writing a test.

Maybe there should be a doc note on how Cell::from_mut works - saying that the resulting cell shares its contents with the original value? I'm not sure that would have helped me, considering how quickly I dismissed it.

Thanks!

The docs could be more explanatory, yeah. Here's a nice article about from_mut (and as_slice_of_cells). It describes from_mut as "downgrading" the &mut T to a &Cell<T>.

(Also it'd be nice if this told you about from_mut instead of[1] replace.)


  1. or in addition to, I guess ↩︎

How else would it work? There's no other reasonable implementation, for multiple reasons:

  • if it copied its argument, why would it bother taking a mutable reference (and hence locking it for the duration of the existence of the returned cell)?
  • if it copied its argument, how could it possibly return a (useful) reference at all? The method obviously can't return a reference to a local cell that was just created within.

That's what I meant above when I wrote:

1 Like
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.