use alloc::sync::Arc;
use core::any::TypeId;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use super::super::error::{DeserializeError, SerializeError};
use super::super::object::SerializableLang;
use super::super::value::{SerialEntry, SerialIndex, TableId};
use super::context::{DeserializeContext, SerializeContext};
pub trait ObjectSerdeDriver<L: SerializableLang>: Send + Sync + 'static {
type Object: ?Sized + Send + Sync + 'static;
type Index: SerialIndex;
fn table_name(&self) -> &'static str;
fn homogeneous_identifier(&self) -> Option<&'static str>;
fn serialize_object(
&self,
object: &Arc<Self::Object>,
cx: &mut SerializeContext<'_, L>,
) -> Result<SerialEntry, SerializeError>;
fn deserialize_object(
&self,
entry: &SerialEntry,
cx: &mut DeserializeContext<'_, L>,
) -> Result<Arc<Self::Object>, DeserializeError>;
}
pub struct TableHandle<D> {
id: TableId,
driver: PhantomData<fn() -> D>,
}
impl<D> TableHandle<D> {
pub(crate) fn new(id: TableId) -> TableHandle<D> {
TableHandle { id, driver: PhantomData }
}
pub fn id(self) -> TableId {
self.id
}
pub fn position<L: SerializableLang>(self, index: u32) -> D::Index
where
D: ObjectSerdeDriver<L>,
{
D::Index::from_parts(self.id, index)
}
pub(crate) fn driver_type_id(self) -> TypeId
where
D: 'static,
{
TypeId::of::<D>()
}
}
impl<D> Clone for TableHandle<D> {
fn clone(&self) -> Self {
*self
}
}
impl<D> Copy for TableHandle<D> {}
impl<D> PartialEq for TableHandle<D> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl<D> Eq for TableHandle<D> {}
impl<D> Hash for TableHandle<D> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl<D> fmt::Debug for TableHandle<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TableHandle")
.field("id", &self.id)
.field("driver", &core::any::type_name::<D>())
.finish()
}
}