• 0 Posts
  • 5 Comments
Joined 1 year ago
cake
Cake day: April 7th, 2025

help-circle
  • Yes, except rust has even stricter requirements - namely that your struct must only contain the “inherited” field and you still need to tell the rust compiler to use the special #[repr(transparent)]!

    This is because the compiler is allowed - under “normal” representation rules - to rearrange basically everything about the memory layout of a struct to better suit its needs. And as far as I know this includes rearranging the location of a field which is arbitrarily deep inside other structures in your struct! As such

    struct A {
      foo: u8,
      bar: u8,
    }
    
    struct B {
      test: u8,
      nested: A,
    }
    

    could theoretically be laid out as bar test foo in memory if the compiler determined that accessing bar at the start of the struct was overall the “best”.

    If, on the other hand, you use #[repr(c)] you get exactly what you just said, although the direct casting may or may not be undefined still. (I currently do not remember the relevant parts of the nomicon or other treaties I have read about this… I really need to get back into programming rust at some point!)


  • Regarding your question about the cast from const* T to UserRef<T>:

    This should be legal as long as UserRef<T> is a #[repr(transparent)] wrapper over a const* T and does most of the magic through its implementation.

    There are some other requirements iirc, but I am not entirely sure about them and some or all of them should be given here automatically through the architecture and/or a proper smart pointer implementation as a transparent wrapper…



  • I am not an expert but I think the actual problem is in the slice::iter first getting an immutable reference to the underlying data with self.0.next() before mapping it into a UserRef<T> which is instant UB because a &T guarantees exclusivity while UserRef<T> explicitly states in its contract that it does not guarantee anything like that, even if mutably borrowed.

    So in essence the problem, as I understood it, is in the step from slice -> reference to value -> User ref of value with the italic part being illegal.