IIUC it's guaranteed for pointer types to Sized objects but not for Sized even though I don't see any good reason why &T, &mut T, Box<T>, *const T, *mut T should have different representations for any T - be it Sized or not. (Arguably also Rc<T> and Arc<T> should have same representation but those are library types, so a bit different case.) Miri doesn't complain about this but given it's just a sanitizer I'm not confident it's sufficient.
And if you're wondering why would I want this: to work around the limitation of HashMap<Foo<Box<[u8]>>, Bar> which requires Borrow for lookups - I want to perform lookup using Foo<&[u8]> as the key.
A reason why they could hypothetically be different is that &[T] and *const [T] could place different invariants on the length field and thus have different niches, which in turn could lead to different ordering of the ptr, len fields.
Maybe if we don't care. But unlike e.g. the question of the actual layout of pointers to unsized types, I don't see any drawback in guaranteeing it's the same for all pointer-like types, and we can definitely make it happen.
*const T, *mut T, &T, &mut T, Box<T> (specifically, only Box<T, Global>), and NonNull<T> are all ABI-compatible with each other for all T.
Being ABI-compatible only makes sense if they also have the same layout. So we should document that IMO, if we do not already.
However, "same layout" does not imply "same niches" and certainly does not mean that Wrapper<T> can be transmuted to Wrapper<U> due to associated types and other shenanigans unsafe code could pull. So even if we do make this pointer guarantee, it is not sound to transmute a HashMap like you suggest, unless HashMap also documents that you can transmute HashMap<K, V> to HashMap<K2, V2> if the layouts of K and K2, as well as V and V2`, are the same. Currently we don't have any guarantee of that sort to my knowledge.
Even for repr(C)? Note also that OP is not transmuting HashMap but Foo which is repr(C) and uses its generic as a field only (not some associated type). So it seems the OP example is sound then, using that ABI guarantee to deduce a layout guarantee.
(Actually, I just realized that impl is unsound to expose to safe code but I believe it should be fine in context of HashMap if properly encapsulated.)
Oh, I misunderstood the text then. I thought it would describe things that happen beyond the code which was shown.
As far as you know HashMap could do just about anything so if it's unsound to expose to safe code and HashMap does not make specific promises then it's still unsound to expose to HashMap.
I think it's sound in practice as long as the borrowed type is private because the reason it is unsound is that you can borrow() a reference with 'static lifetime (or in general something longer than what it had) and then cause use-after-free (I tested this) but HashMap operates on generic U: Eq + Hash where Key: Borrow<U> and has no additional knowledge that would allow such operation - it can only compare it and hash it while having it behind the reference coming out of the Borrow trait which correctly restricts the lifetime. Any is also unusable because the 'static bound is not there. Perhaps there is a way for it to break with specialization on Clone but this can be avoided by making the type intentionally NOT implement Clone or any trait other than Eq, PartialEq, Hash, and auto traits (which are markers only, so don't' allow any operations).
So then the responsibility falls on the implementations of PartialEq and Hash traits on that type which can be carefully designed to not accidentally do something wrong - but really don't have to because just using #[derive(PartialEq, Hash)] makes it forward to implementation for [u8] which again cannot know that the lifetime appears to be longer, including using specialization tricks.
But if you can find a hole in this reasoning I'm all ears!
That is an argument based on parametricity, which is not generally valid reasoning in Rust. There are various ways (type_id, specialization, try_as_dyn) via which HashMap could special-case a type and therefore break the "no additional knowledge" argument.
None of those seem to allow seeing the lifetimes and it doesn't appear that any kind of specialization-like feature will ever be built on lifetimes. So I think for any reference contained inside &'a T the caller must assume it does NOT live longer than 'a. The only thing that would allow it is a trait explicitly implemented for something longer but simply not implementing that trait works as long as the type is private.
If there is an actual desire to add a mechanism to inspect the lifetimes of type parameters then I agree that this is problematic.
There's an additional argument: if the offending field is private then anything that accesses it outside of defining module using some specialization-like hacks violates the privacy which is broken at best, unsound at worst.
Technically, the code you showed is perfectly sound. But it’d be unsound if user code could get a &B from a &Foo<B>, which you presumably want to be possible.
I originally wanted it possible but that would be unsound. However, it's not really needed for lookups (the struct can be cheaply reconstructed) and there's even a nice alternative:
// Doesn't need the real lifetime because it's enforced differently
// has no API to obtain the inner reference with lifetime longer than an existing &BoxOrRef
// NOT Copy, or Clone
#[repr(transparent)]
pub struct BoxOrRef<T>(&'static T);
impl<T> BoxOrRef<T> {
pub fn reborrow(&self) -> &T {
&self.0
}
}
Then Borrow<Foo<BoxOrRef<[u8]>> for Foo<Box<[u8]>> is fully sound.
I haven't seen anything like this in the wild, so looks like I invented a new pattern?
If you can write any safe code inside main that abuses any of the Borrow impls I will be more than impressed.
Most importantly BoxOrRef is always behind a shared reference - never owned, or behind a &mut. So no drop_in_place is happening on it ever. Anything that wants to obtain 'static ref would have to somehow break the privacy of the module and if such thing becomes allowed a shitload of code will suddenly become unsound.
FWIW, given an owned BoxOrRef, one can get the field out (via Box::leak). So this crucially relies on the lifetime in the return type of fn borrow(&self) -> &Foo<BoxOrRef<[u8]>>.
This feels to me like a variant of the well-known (or at least, old) observation that &'a Box<T> and &'a &'a T are basically the same type and it's sound to transmute between them. You just have a Foo<_> in between the & and the Box.