use core::{fmt, marker::PhantomData};
use crate::Operator;
use super::{anymap::Map, Context};
#[derive(Debug)]
pub struct Value<T> {
pub(crate) value: T,
pub(crate) context: Context,
}
impl<T> Value<T> {
#[inline]
pub(super) fn with_data(value: T, data: Map) -> Self {
Self {
value,
context: Context::with_data(data),
}
}
#[inline]
pub fn value(&self) -> &T {
&self.value
}
#[inline]
pub fn value_mut(&mut self) -> &mut T {
&mut self.value
}
#[inline]
pub fn context(&self) -> &Context {
&self.context
}
#[inline]
pub fn context_mut(&mut self) -> &mut Context {
&mut self.context
}
pub fn apply(&mut self, f: impl FnOnce(&mut T, &mut Context)) {
f(&mut self.value, &mut self.context)
}
pub fn map<U>(self, f: impl FnOnce(T, &mut Context) -> U) -> Value<U> {
let Self { value, mut context } = self;
Value {
value: f(value, &mut context),
context,
}
}
pub(super) fn into_inner(self) -> T {
self.value
}
pub fn as_ref(&self) -> ValueRef<'_, T> {
ValueRef {
value: &self.value,
context: &self.context,
}
}
}
pub struct Input<T>(PhantomData<fn() -> T>);
impl<T> fmt::Debug for Input<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Input").finish()
}
}
impl<T> Clone for Input<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Input<T> {}
impl<T> Default for Input<T> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<T> Operator<Value<T>> for Input<T> {
type Output = Value<T>;
#[inline]
fn next(&mut self, input: Value<T>) -> Self::Output {
input
}
}
pub fn input<T>() -> Input<T> {
Input(PhantomData)
}
#[derive(Debug)]
pub struct ValueRef<'a, T> {
pub(crate) value: &'a T,
pub(crate) context: &'a Context,
}
impl<'a, T> ValueRef<'a, T> {
#[inline]
pub fn value(&self) -> &'a T {
self.value
}
#[inline]
pub fn context(&self) -> &'a Context {
self.context
}
}