stable_deref_trait icon indicating copy to clipboard operation
stable_deref_trait copied to clipboard

Document StableDeref for fat pointers

Open joshlf opened this issue 7 years ago • 4 comments

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.

joshlf avatar May 17 '18 05:05 joshlf

Is it even possible for the length of a DST to change?

Storyyeller avatar May 17 '18 14:05 Storyyeller

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]
    }
}

joshlf avatar May 17 '18 14:05 joshlf

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).

philipc avatar Jul 29 '18 04:07 philipc

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.

joshlf avatar Jul 29 '18 05:07 joshlf