How to get internal compatibility by type of copy?

I have several types of Copy , and I am very grateful for the convenience of using Copy .

I would like one of these types to contain a mutable field using the Interior Mutability function, as in cell::Cell . There are probably other solutions to the problem I'm trying to solve, but the internal mutability is cheap. I like it cheaply.

However, it turns out that cell::Cell not Copy , and from the comments Copy unlikely to become, as the attendants fear that this will be error prone.

OP comment is my current beacon of hope:

This is not an absolute end of the world, if it is not for my own data structures (since I can just make my own version of Cell )

Although I do not see how they intend to achieve this success.

The main question I have is that UnsafeCell :

  • is required to implement internal interchangeability,
  • not Copy .

Which seems to close the door to any hope of implementing CopyCell if I miss the trick (the path to unsafe impl Copy ?).


MCVE :

 #[derive(Clone, Copy)] struct HelloWorld(Cell<u32>); 
  | 3 | #[derive(Clone, Copy)] | ^^^^ 4 | struct HelloWorld(Cell<u32>); | ---------- this field does not implement `Copy` 

What should I replace Cell with HelloWorld as Copy ?


Note: at the moment, the only way to see the desired result is to use &Cell<T> ; with all the consequences of life.

+5
source share
1 answer

I think there is a good reason that UnsafeCell does not implement Copy : it would be unsafe in the general case. Reading from UnsafeCell is an unsafe operation, as shown by the signature of the get method: it returns a raw pointer, and dereferencing a raw pointer is an unsafe operation. The copy implicitly read the value that could race with another stream written to the same UnsafeCell . Cell does not have this race because it is !Sync (i.e. two threads cannot access the same Cell ).

Personally, I just used Clone::clone instead of messing around with links. Cell clone is #[inline] , so it is very likely that the call will be optimized in build versions.

+3
source

Source: https://habr.com/ru/post/1275349/


All Articles