use std::{error::Error, rc::Rc}; use crate::func::*; pub trait Context { type T: Monad; fn hash(s: &[u8]) -> Hash; } type Hash = [u8; 32]; pub trait Serializer { fn write(&mut self, buf: &[u8]); } impl Serializer for F { fn write(&mut self, buf: &[u8]) { self(buf); } } pub trait Mentionable { type Fctr: Factory; fn serialize(&self, serializer: F); fn factory(&self) -> Self::Fctr; fn topology(&self) -> Hash; } pub trait Deserializer { fn read_n_const(&mut self) -> Result<[u8; N], &[u8]>; fn read_n(&mut self, n: usize) -> &[u8]; fn read_all(&mut self, n: usize) -> &[u8]; } pub trait Factory: Clone { type Mtbl: Mentionable; type ParseError: Error; fn deserialize(&self, deserializer: F) -> Result; } pub trait Origin<'a, Ctx: Context>: 'a { type Mtbl: Mentionable; fn factory(&self) -> >::Fctr; fn resolve(&self) -> <::T as WeakFunctor>::F<'a, Rc>; } struct LocalOrigin(Rc); impl<'a, Ctx: 'a + Context, A: 'a + Mentionable> Origin<'a, Ctx> for LocalOrigin { type Mtbl = A; fn factory(&self) -> >::Fctr { self.0.factory() } fn resolve(&self) -> <::T as WeakFunctor>::F<'a, Rc> { ::pure(self.0.clone()) } } impl From for LocalOrigin { fn from(value: A) -> Self { LocalOrigin(value.into()) } } #[derive(Clone)] pub struct Point<'a, Ctx: Context, A: Mentionable> { pub point: Hash, pub origin: Rc>, } impl<'a, Ctx: 'a + Context, A: 'a + Mentionable> Point<'a, Ctx, A> { fn prepare_bytes_for_hashing(mentioned: &A) -> Vec { let mut vec = mentioned.topology().to_vec(); mentioned.serialize(|x: &[u8]| vec.extend(x.iter())); vec } fn from_fields(point: Hash, origin: Rc>) -> Self { Point { point, origin } } fn from_values>(point: Hash, origin: O) -> Self { Self::from_fields(point, Rc::new(origin)) } pub fn resolve(&self) -> <::T as WeakFunctor>::F<'a, Rc> { self.origin.resolve() } } impl<'a, Ctx: 'a + Context, A: 'a + Mentionable> From for Point<'a, Ctx, A> { fn from(value: A) -> Self { Self::from_values( Ctx::hash(Self::prepare_bytes_for_hashing(&value).as_slice()), LocalOrigin::from(value), ) } }