vorner / arc-swap

Support atomic operations on Arc itself
Apache License 2.0
778 stars 31 forks source link

Storing `dyn Trait` and `str` without `Box<str>`. #83

Closed BratSinot closed 1 year ago

BratSinot commented 1 year ago

Greetings!

Hypotetically, because ArcSwapOption inside uses Arc it can store dyn Trait and str directly without double boxing. But in current implementation RefCnt::Base becoming type Base = str; / type Base = dyn Trait. Hypotetically, that part can be implemented with void raw pointers. Is that possible and is the game worth the candle?

vorner commented 1 year ago

Hello

I don't think what you suggest would work.

The issue with dyn Trait, str, slices and other unsized types is that pointers to them are fat pointers. The pointer is 2 words large ‒ in case of str and slices, it is pointer to the beginning and the length, in case of dyn Trait it is pointer to the object and pointer to the vtable.

This is an inherent property of any representation of the pointer. If you manage to somehow cast such pointer to usize or to a void raw pointer or to anything like that, you lose half of the information and have no way to recover it later on ‒ so that one is not possible. And Rust AFAIK doesn't offer a way to store 2-word value atomically. That's the reason why AtomicPtr<str> or anything like that doesn't exist.

I believe this is therefore not possible to support, so I'll close this issue. If you believe I'm wrong there, I'd ask you to post some kind of minimal example of passing the pointer from one thread to another atomically and recovering the original value on the other side.