From e823f58e774f1d57386e4e9385cc806699641738 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 13 Dec 2023 12:11:26 -0500 Subject: [PATCH] References from immortal can be static --- src/immortal.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/immortal.rs b/src/immortal.rs index f9e7103..0d24d16 100644 --- a/src/immortal.rs +++ b/src/immortal.rs @@ -6,6 +6,7 @@ * https://www.zerotier.com/ */ +use std::mem::transmute; use std::ops::Deref; /// Container for an object that never dies, by design (leaks on drop) @@ -19,20 +20,19 @@ use std::ops::Deref; /// /// Semantics are similar to Arc<> in that only non-mutable references can be obtained and /// the object can be cloned. These can also be copied, as they are just pointers. -#[derive(Clone, Copy)] -pub struct Immortal(*mut T); +pub struct Immortal(&'static T); impl Immortal { #[inline(always)] pub fn new(obj: T) -> Self { - Self(Box::into_raw(Box::new(obj))) + Self(unsafe { transmute(&*Box::into_raw(Box::new(obj))) }) } } impl AsRef for Immortal { #[inline(always)] - fn as_ref(&self) -> &T { - unsafe { &*self.0 } + fn as_ref(&self) -> &'static T { + self.0 } } @@ -40,8 +40,15 @@ impl Deref for Immortal { type Target = T; #[inline(always)] - fn deref(&self) -> &Self::Target { - unsafe { &*self.0 } + fn deref(&self) -> &'static Self::Target { + self.0 + } +} + +impl Clone for Immortal { + #[inline(always)] + fn clone(&self) -> Self { + Self(self.0) } }