]> git.lizzy.rs Git - rust.git/commit
Rollup merge of #97373 - dimpolo:cell_dispatch_from_dyn, r=dtolnay
authorMatthias Krüger <matthias.krueger@famsik.de>
Thu, 26 Jan 2023 06:53:21 +0000 (07:53 +0100)
committerGitHub <noreply@github.com>
Thu, 26 Jan 2023 06:53:21 +0000 (07:53 +0100)
commite0d71f500cabca8f8bd1b660bbd292bf451b1bab
treefbffdf6734cba4d9c39b9f8f727be76eef5da8f6
parent885bf628879310b885721e1fdd91ea2cbca9311f
parentaf58854168f2ae6b0af89d7945584cb78e276193
Rollup merge of #97373 - dimpolo:cell_dispatch_from_dyn, r=dtolnay

impl DispatchFromDyn for Cell and UnsafeCell

After some fruitful discussion on [Internals](https://internals.rust-lang.org/t/impl-dispatchfromdyn-for-cell-2/16520) here's my first PR to rust-lang/rust 🎉

Please let me know if there's something I missed.

This adds `DispatchFromDyn` impls for `Cell`, `UnsafeCell` and `SyncUnsafeCell`.
An existing test is also expanded to test the `Cell` impl (which requires the `UnsafeCell` impl)

The different `RefCell` types can not implement `DispatchFromDyn` since they have more than one (non ZST) field.

&nbsp;

**Edit:**
### What:
These changes allow one to make types like `MyRc`(code below), to be object safe method receivers after implementing `DispatchFromDyn` and `Deref` for them.

This allows for code like this:
```rust
struct MyRc<T: ?Sized>(Cell<NonNull<RcBox<T>>>);

/* impls for DispatchFromDyn, CoerceUnsized and Deref for MyRc*/

trait Trait {
    fn foo(self: MyRc<Self>);
}

let impls_trait = ...;
let rc = MyRc::new(impls_trait) as MyRc<dyn Trait>;
rc.foo();
```

Note: `Cell` and `UnsafeCell` won't directly become valid method receivers since they don't implement `Deref`. Making use of these changes requires a wrapper type and nightly features.

### Why:
A custom pointer type with interior mutability allows one to store extra information in the pointer itself.
These changes allow for such a type to be a method receiver.

### Examples:
My use case is a cycle aware custom `Rc` implementation that when dropping a cycle marks some references dangling.

On the [forum](https://internals.rust-lang.org/t/impl-dispatchfromdyn-for-cell/14762/8) andersk mentioned that they track if a `Gc` reference is rooted with an extra bit in the reference itself.