kproc 0.7.0

Knowledge Processing library.
Documentation
//! Cache values, used to avoid a stream to clog

pub use kproc_pmacros::Processor;
use std::collections::LinkedList;

use crate::processor::{InputStreams, OutputStreams};
use crate::{processor, Result};

/// Inputs to cache
#[derive(Clone, InputStreams)]
pub struct Inputs<T>
where
  T: Clone,
{
  t: T,
}

/// Outputs to cache
#[derive(Clone, OutputStreams)]
pub struct Outputs<T>
where
  T: Clone,
{
  t: T,
}

/// Allow to cache a value in a kproc graph.
#[derive(Processor)]
#[streams(Inputs<T>, Outputs<T>)]
pub struct Cache<T>
where
  T: Clone,
{
  _t: std::marker::PhantomData<T>,
}

impl<T> processor::Processor for Cache<T>
where
  T: Clone,
{
  // async fn process_one(&self, inputs: Self::Inputs) -> Self::Outputs {}
  async fn start(self, mut inputs: Self::InputStreams, mut outputs: Self::OutputStreams)
  {
    let mut cache = LinkedList::<T>::new();
    loop
    {
      let i = inputs.next().await.unwrap();
      if outputs.is_full()
      {
        cache.push_back(i.t);
      }
      else
      {
        while !cache.is_empty() && !outputs.is_full()
        {
          let _ = outputs
            .next(Outputs {
              t: cache.pop_front().unwrap(),
            })
            .await;
        }
        if outputs.is_full()
        {
          cache.push_back(i.t);
        }
        else
        {
          let _ = outputs.next(Outputs { t: i.t }).await;
        }
      }
    }
  }
}