radn-rs/src/rstd/atomic/atomic_object.rs
2023-06-28 15:06:27 +00:00

97 lines
2.2 KiB
Rust

//! Provides [Atomic]-[Mentionable] interface.
use std::ops::Deref;
use super::*;
/// Generic implementation of a [Mentionable] for [Atomic]s.
#[derive(Clone)]
pub struct AtomicObject<A: Atomic> {
atomic: A,
}
impl<A: Atomic> From<A> for AtomicObject<A> {
fn from(value: A) -> Self {
Self { atomic: value }
}
}
impl<A: Atomic> AsRef<A> for AtomicObject<A> {
fn as_ref(&self) -> &A {
&self.atomic
}
}
impl<A: Atomic> Deref for AtomicObject<A> {
type Target = A;
fn deref(&self) -> &Self::Target {
&self.atomic
}
}
impl<A: Atomic> Serializable for AtomicObject<A> {
fn serialize(&self, serializer: &mut dyn Serializer) {
self.atomic.serialize(serializer)
}
}
impl<'a, Ctx: Context<'a>, A: Atomic> Mentionable<'a, Ctx> for AtomicObject<A> {
type Fctr = AtomicFactory<A>;
fn factory(&self) -> Self::Fctr {
AtomicFactory::new()
}
fn topology(&self) -> Hash {
Ctx::hash(b"")
}
fn points_typed(&self, _points: &mut impl TakesPoints<'a, Ctx>) {}
}
/// Generic implementation of a [Factory] for [Atomic]s.
pub struct AtomicFactory<A: Atomic> {
_pd: PhantomData<A>,
}
impl<A: Atomic> AtomicFactory<A> {
fn new() -> Self {
AtomicFactory { _pd: PhantomData }
}
}
impl<A: Atomic> Clone for AtomicFactory<A> {
fn clone(&self) -> Self {
Self::new()
}
}
impl<'a, Ctx: Context<'a>, A: Atomic> Factory<'a, Ctx> for AtomicFactory<A> {
type Mtbl = AtomicObject<A>;
type ParseError = A::AParseError;
fn deserialize(&self, dectx: &mut dyn DeCtx<'a, Ctx>) -> ParseResult<'a, Ctx, Self> {
Ok(A::o_deserialise(dectx)?.into())
}
fn extend(&self, mentionable: Self::Mtbl, tail: &[u8]) -> ParseResult<'a, Ctx, Self> {
Ok(A::a_extend(mentionable.atomic, tail)?.into())
}
}
/// Extension trait to provide method-like utilities associated with [AtomicObject]s.
pub trait AtomicObjectExt: Atomic {
/// Shorthand for getting specific [`AtomicFactory`].
fn f() -> AtomicFactory<Self> {
AtomicFactory::new()
}
/// Shorthand for getting specific [`AtomicObject`].
fn m(self) -> AtomicObject<Self> {
self.into()
}
}
impl<A: Atomic> AtomicObjectExt for A {}