nibblecode 0.1.0

A serialization format based on rkyv
Documentation
//! An archived version of `Box`.

use core::borrow::Borrow;
use core::fmt;
use core::fmt::{Debug, Display, Formatter, Pointer};
use core::hash::{Hash, Hasher};
use core::ops::Deref;
use std::cmp::Ordering;
use std::marker::{PhantomData, PhantomPinned};
use std::ops::DerefMut;

use crate::primitive::ArchivedUsize;

/// An archived [`Box`].
pub struct ArchivedBox<T> {
	pub(crate) offset: ArchivedUsize,
	pub(crate) _phantom_data: PhantomData<T>,
	pub(crate) _phantom_pinned: PhantomPinned,
}

impl<T> ArchivedBox<T> {
	fn as_ptr(&self) -> *const T {
		unsafe { <*const ArchivedBox<T>>::cast::<u8>(self).add(self.offset.to_native() as usize) }
			.cast()
	}

	/// Returns a reference to the value of this archived box.
	#[must_use]
	pub fn get(&self) -> &T {
		unsafe { &*self.as_ptr() }
	}

	/// Returns a sealed mutable reference to the value of this archived box.
	#[must_use]
	pub fn get_mut(&mut self) -> &mut T {
		unsafe { &mut *self.as_ptr().cast_mut() }
	}
}

impl<T> AsRef<T> for ArchivedBox<T> {
	fn as_ref(&self) -> &T {
		self.get()
	}
}

impl<T> Borrow<T> for ArchivedBox<T> {
	fn borrow(&self) -> &T {
		self.get()
	}
}

impl<T> Debug for ArchivedBox<T> {
	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		f.debug_tuple("ArchivedBox").field(&self.offset).finish()
	}
}

impl<T> Deref for ArchivedBox<T> {
	type Target = T;

	fn deref(&self) -> &T {
		self.get()
	}
}

impl<T> DerefMut for ArchivedBox<T> {
	fn deref_mut(&mut self) -> &mut T {
		self.get_mut()
	}
}

impl<T: Display> Display for ArchivedBox<T> {
	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		self.get().fmt(f)
	}
}

impl<T: Eq> Eq for ArchivedBox<T> {}

impl<T: Hash> Hash for ArchivedBox<T> {
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.get().hash(state);
	}
}

impl<T: Ord> Ord for ArchivedBox<T> {
	fn cmp(&self, other: &Self) -> Ordering {
		self.as_ref().cmp(other.as_ref())
	}
}

impl<T: PartialEq<U>, U> PartialEq<ArchivedBox<U>> for ArchivedBox<T> {
	fn eq(&self, other: &ArchivedBox<U>) -> bool {
		self.get().eq(other.get())
	}
}

impl<T: PartialOrd> PartialOrd for ArchivedBox<T> {
	fn partial_cmp(&self, other: &ArchivedBox<T>) -> Option<Ordering> {
		self.get().partial_cmp(other.get())
	}
}

impl<T> Pointer for ArchivedBox<T> {
	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		Pointer::fmt(&self.as_ptr(), f)
	}
}