use crate::ContentPath;
use std::{
fmt::Debug,
ops::{Deref, DerefMut},
};
pub trait ContentType: Copy + Eq + PartialEq + Debug + Ord + PartialOrd {
const COUNT: u16;
fn as_u16(&self) -> u16;
fn from_u16(value: u16) -> Option<Self>;
}
pub trait Content<T: ContentType> {
fn content_type(&self) -> Option<T> {
None
}
fn path(&self) -> &ContentPath;
fn size(&self) -> u64;
fn read(&mut self, offset: u64, count: u32) -> Option<&[u8]>;
}
impl ContentType for bool {
const COUNT: u16 = 2;
fn as_u16(&self) -> u16 {
*self as u16
}
fn from_u16(value: u16) -> Option<Self> {
if value == 0 {
Some(false)
} else if value == 1 {
Some(true)
} else {
None
}
}
}
#[derive(Debug, Copy, Clone)]
pub(crate) struct ContentPtr<T: ContentType> {
content: *mut dyn Content<T>,
}
impl<T: ContentType> ContentPtr<T> {
#[inline(always)]
pub(crate) fn new(content: &mut dyn Content<T>) -> Self {
Self {
content: unsafe { std::mem::transmute::<*mut dyn Content<T>, *mut (dyn Content<T> + 'static)>(content as *mut _) },
}
}
#[inline(always)]
pub(crate) fn as_mut(&mut self) -> &mut dyn Content<T> {
unsafe { &mut *self.content }
}
#[inline(always)]
pub(crate) fn as_ref(&self) -> &dyn Content<T> {
unsafe { &*self.content }
}
}
pub struct OwnedContentPtr<T: ContentType> {
content: *mut dyn Content<T>,
}
impl<T: ContentType> OwnedContentPtr<T> {
#[inline(always)]
pub(crate) fn new(content: ContentPtr<T>) -> Self {
Self { content: content.content }
}
}
impl<T: ContentType> Deref for OwnedContentPtr<T> {
type Target = dyn Content<T>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*self.content }
}
}
impl<T: ContentType> DerefMut for OwnedContentPtr<T> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.content }
}
}