Should RefCast be an unsafe trait?
- Dominant language
- Rust
- Stars
- 224
- Forks
- 20
- Avg merge
- 1m
- Merged PRs (30d)
- 1
Description
The documentation states that `RefCast` "Safely cast &T to &U where the struct U contains a single field of type T."
I've thought about implementing an extension crate for casting slices (yes, slices again), something like this:
```rust
pub trait RefCastSlice: Sized {
type From;
fn ref_cast_slice(from: &[Self::From]) -> &[Self];
}
impl RefCastSlice for T
where
T: ref_cast::RefCast,
::From: Sized,
{
type From = ::From;
fn ref_cast_slice(from: &[Self::From]) -> &[Self] {
// Safety: ref_cast::RefCast invariants.
unsafe { std::slice::from_raw_parts(from.as_ptr() as _, from.len()) }
}
}
```
However, it would only works for `RefCast` implemented with the macro.
Manually I can implement something like this:
```rust
pub struct MySmallStruct { /* any content */ }
pub struct MyBigStruct {
a: u32,
b: MySmallStruct,
}
// Because I can
impl ref_cast::RefCast for MySmallStruct {
type From = MyBigStruct;
fn ref_cast(from: &Self::From) -> &Self {
&from.b
}
fn ref_cast_mut(from: &mut Self::From) -> &mut Self {
&mut from.b
}
}
```
And it will break my slice implementation completely, despite promises in the RefCast documentation.
Making the trait unsafe and requiring that `Self` and `Self::From` to have same layout would make the crate more usable and would solve a problem users need (though it a breaking change, of course).
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.