#![allow(unused)] use core::fmt::{Debug, Display, Formatter, UpperHex}; use core::marker::PhantomData; use core::mem::transmute; use core::ops::{ControlFlow, Deref, DerefMut, Index, IndexMut}; pub struct VirtualOffset(PhantomData); impl VirtualOffset { #[inline(always)] pub(crate) fn vo_as_ptr(&self) -> *mut T { ((self as *const _ as usize) + O) as *mut T } #[inline(always)] pub(crate) fn offset() -> usize { return O; } /// gets a ref to the underlying type /// just an alias for the deref trait so it doesnt need to be imported pub fn r#ref(&self) -> &T { self.deref() } } impl Deref for VirtualOffset { type Target = T; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { transmute(((self as *const _ as usize) + O) as *const T)} } } impl DerefMut for VirtualOffset { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { unsafe { transmute(((self as *mut _ as usize) + O) as *mut T)} } } // ============================== // Index // ============================== impl, const O: usize> Index for VirtualOffset { type Output = T::Output; fn index(&self, index: I) -> &Self::Output { unsafe { &*self.vo_as_ptr() }.index(index) } } impl, const O: usize> IndexMut for VirtualOffset { fn index_mut(&mut self, index: I) -> &mut Self::Output { unsafe { &mut *self.vo_as_ptr() }.index_mut(index) } } // ============================== // Display + Debug // ============================== // Proxy the Display trait impl Display for VirtualOffset { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.deref().fmt(f) } } // Proxy the UpperHex trait impl UpperHex for VirtualOffset { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.deref().fmt(f) } } // Proxy the Debug trait (in debug builds) impl Debug for VirtualOffset { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.deref().fmt(f) } } // ============================== // Macro // ============================== #[macro_export] macro_rules! struct_offset { ($offset:literal, $type:ty) => { $crate::VirtualOffset<$type, $offset> } }