Make node trait consume self

This commit is contained in:
Dennis
2022-08-19 18:58:17 +02:00
committed by Keavon Chambers
parent 12b33da083
commit bdad7aca47
10 changed files with 286 additions and 188 deletions

View File

@@ -1,36 +1,48 @@
use core::marker::PhantomData;
use crate::Node;
use self::color::Color;
pub mod color;
#[derive(Debug, Clone, Copy)]
pub struct GrayscaleNode;
impl<'n> Node<'n, Color> for GrayscaleNode {
impl Node<Color> for GrayscaleNode {
type Output = Color;
fn eval(&'n self, color: Color) -> Color {
fn eval(self, color: Color) -> Color {
let avg = (color.r() + color.g() + color.b()) / 3.0;
Color::from_rgbaf32(avg, avg, avg, color.a()).expect("Grayscale node created an invalid color")
Color::from_rgbaf32_unchecked(avg, avg, avg, color.a())
}
}
impl<'n> Node<Color> for &'n GrayscaleNode {
type Output = Color;
fn eval(self, color: Color) -> Color {
let avg = (color.r() + color.g() + color.b()) / 3.0;
Color::from_rgbaf32_unchecked(avg, avg, avg, color.a())
}
}
pub struct ForEachNode<'n, I: Iterator<Item = S>, MN: Node<'n, S>, S>(pub MN, PhantomData<&'n (I, S)>);
pub struct ForEachNode<MN>(pub MN);
impl<'n, I: Iterator<Item = S>, MN: Node<'n, S, Output = ()>, S> Node<'n, I> for ForEachNode<'n, I, MN, S> {
impl<'n, I: Iterator<Item = S>, MN: 'n, S> Node<I> for &'n ForEachNode<MN>
where
&'n MN: Node<S, Output = ()>,
{
type Output = ();
fn eval(&'n self, input: I) -> Self::Output {
input.for_each(|x| self.0.eval(x))
fn eval(self, input: I) -> Self::Output {
input.for_each(|x| (&self.0).eval(x))
}
}
pub struct MutWrapper<'n, N: Node<'n, T, Output = T>, T: Clone>(pub N, PhantomData<&'n T>);
pub struct MutWrapper<N>(pub N);
impl<'n, T: Clone, N: Node<'n, T, Output = T>> Node<'n, &'n mut T> for MutWrapper<'n, N, T> {
impl<'n, T: Clone, N> Node<&'n mut T> for &'n MutWrapper<N>
where
&'n N: Node<T, Output = T>,
{
type Output = ();
fn eval(&'n self, value: &'n mut T) {
*value = self.0.eval(value.clone());
fn eval(self, value: &'n mut T) {
*value = (&self.0).eval(value.clone());
}
}
@@ -41,8 +53,9 @@ mod test {
#[test]
fn map_node() {
let array = &mut [Color::from_rgbaf32(1.0, 0.0, 0.0, 1.0).unwrap()];
let map = ForEachNode(MutWrapper(GrayscaleNode, PhantomData), PhantomData);
map.eval(array.iter_mut());
(&GrayscaleNode).eval(Color::from_rgbf32_unchecked(1., 0., 0.));
let map = ForEachNode(MutWrapper(GrayscaleNode));
(&map).eval(array.iter_mut());
assert_eq!(array[0], Color::from_rgbaf32(0.33333334, 0.33333334, 0.33333334, 1.0).unwrap());
}
}