From 36a12f3053f7ca782eaa379127f418c7944d8c17 Mon Sep 17 00:00:00 2001 From: timofey Date: Sun, 3 Sep 2023 19:53:29 +0000 Subject: [PATCH] `rstd::tcast` --- src/rstd.rs | 1 + src/rstd/tcast.rs | 78 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 src/rstd/tcast.rs diff --git a/src/rstd.rs b/src/rstd.rs index ae84ec0..70b6e83 100644 --- a/src/rstd.rs +++ b/src/rstd.rs @@ -12,6 +12,7 @@ mod local_origin; pub mod nullable; pub mod point; pub mod singular; +pub mod tcast; pub mod tracing; pub mod typeless; mod wrapped_origin; diff --git a/src/rstd/tcast.rs b/src/rstd/tcast.rs new file mode 100644 index 0000000..144cae9 --- /dev/null +++ b/src/rstd/tcast.rs @@ -0,0 +1,78 @@ +use std::sync::Arc; + +use crate::rcore::*; + +use super::{singular::*, *}; + +pub trait CastMentionable<'a, Ctx: SingularCtx<'a>>: Mentionable<'a, Ctx> { + fn m_cast>(&self, factory: &Fctr<'a, A>) -> ParseResultA<'a, A> { + factory.parse_slice( + &self.bytes(), + &SingularResolver::from_mentionable(self).robust(), + ) + } +} + +impl<'a, Ctx: SingularCtx<'a>, B: Mentionable<'a, Ctx>> CastMentionable<'a, Ctx> for B {} + +struct CastedOrigin { + origin: Arc, + factory: F, +} + +impl<'a, Ctx: SingularCtx<'a>, O: ?Sized + Origin<'a, Ctx>, F: Factory<'a, Ctx>> Origin<'a, Ctx> + for CastedOrigin +{ + type Mtbl = F::Mtbl; + + fn factory(&self) -> OFctr<'a, Ctx, Self> { + self.factory.clone() + } + + fn resolve(self: Arc) -> Resolution<'a, Ctx, Self::Mtbl> + where + OFctr<'a, Ctx, Self>: FactoryParse<'a, Ctx>, + { + self.clone().origin.resolve_bytes_map(move |resolved| { + resolved + .map_err(ResolutionError::Lookup) + .and_then(|(src, resolver)| { + self.factory + .parse_slice(&src, &resolver) + .map_err(ResolutionError::Parse) + }) + .map(Arc::new) + }) + } + + fn resolve_bytes(self: Arc) -> HashResolution<'a, Ctx> { + self.origin.ref_resolve_bytes() + } +} + +pub trait CastOrigin<'a, Ctx: SingularCtx<'a>>: Origin<'a, Ctx> { + fn o_cast>( + self: &Arc, + factory: Fctr<'a, A>, + ) -> Arc> { + Arc::new(CastedOrigin { + origin: self.clone(), + factory, + }) as _ + } +} + +impl<'a, Ctx: SingularCtx<'a>, O: ?Sized + Origin<'a, Ctx>> CastOrigin<'a, Ctx> for O {} + +pub trait CastPoint<'a, Ctx: SingularCtx<'a>> { + fn p_cast>(self, factory: Fctr<'a, A>) -> Point<'a, Ctx, A>; +} + +impl<'a, Ctx: SingularCtx<'a>, B: Mentionable<'a, Ctx>> CastPoint<'a, Ctx> for Point<'a, Ctx, B> { + fn p_cast>(self, factory: Fctr<'a, A>) -> Point<'a, Ctx, A> { + Point { + point: self.point, + origin: self.origin.o_cast(factory), + } + } +}