Skip to content

Commit

Permalink
clearer pointer casting
Browse files Browse the repository at this point in the history
  • Loading branch information
KGrewal1 committed Nov 28, 2024
1 parent 96c4df4 commit 0f3e0fa
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions nativelink-util/src/store_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,14 @@ where
//
// As such we cast through pointers to convert from one to the other: this is sound
// as we use #[repr(transparent)] to ensure the same in memory layout
let ptr = self as *const StoreKey<'b>;
let ptr = ptr.cast::<StoreKeyBorrow<'a>>();
unsafe { ptr.as_ref().unwrap() }

// turn a reference to `StoreKey<'b>` into a pointer to `StoreKeyBorrow<'a>`
let ptr = (std::ptr::from_ref::<StoreKey<'b>>(self)).cast::<StoreKeyBorrow<'a>>();
// turn this pointer back into a reference
// we know this pointer is non null as it is just derived from a reference above
// and that it is a valid StoreKeyBorrow<'a>, as it has the same layout and as its
// lifetime is shorter than the pointer it derives from (it is safe to shorten covariant lifetimes)
unsafe { &*ptr }
}
}

Expand Down

0 comments on commit 0f3e0fa

Please sign in to comment.