stable_deref_trait
stable_deref_trait copied to clipboard
Document StableDeref for fat pointers
I'm wondering whether StableDeref implies requirements on fat pointers (e.g., that the length of a DST won't change). If so, I'd like to be able to use StableDeref for that use case, so it'd be nice if that requirement were documented.
Is it even possible for the length of a DST to change?
Yep:
extern crate rand;
struct UnstableSlice<T>([T]);
impl<T> Deref for UnstableSlice<T> {
type Target = [T];
fn deref(&self) -> &[T] {
let len = self.0.len();
&self.0[..rand::random() % len]
}
}
Do you have a more realistic example of a type that changes the length like that? It seems to me that in practice having the length change would imply mutation, whereas the StableDeref guarantee is only for moves, not mutation. I don't see any problem with requiring a fixed length, and I had already assumed StableDeref required that (and I would expect that behaviour for Deref too, even if you can write code that behaves otherwise).
I don't have an example. The code I was hoping to use StableDeref for uses unsafe under the hood, and provides a safe API. So even if such code is unlikely to arise in practice, it'd still be unsound for me to rely on StableDeref if it didn't provide that guarantee.
If you're curious, the crate in question is here; see the ByteSlice trait and the comments around it for a sense of how I was hoping to use StableDeref.