From 0f3e0fa774ecc1a4270ab37fbdbdf9ee2f9a906b Mon Sep 17 00:00:00 2001 From: Kirpal Grewal Date: Thu, 28 Nov 2024 12:17:15 +0000 Subject: [PATCH] clearer pointer casting --- nativelink-util/src/store_trait.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/nativelink-util/src/store_trait.rs b/nativelink-util/src/store_trait.rs index fefb3a985..02869b583 100644 --- a/nativelink-util/src/store_trait.rs +++ b/nativelink-util/src/store_trait.rs @@ -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::>(); - unsafe { ptr.as_ref().unwrap() } + + // turn a reference to `StoreKey<'b>` into a pointer to `StoreKeyBorrow<'a>` + let ptr = (std::ptr::from_ref::>(self)).cast::>(); + // 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 } } }