ed_journals/modules/state/models/
state_container.rsuse crate::state::models::feed_result::FeedResult;
use crate::state::traits::state_resolver::StateResolver;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt::{Debug, Formatter};
use std::mem;
use std::ops::{Deref, DerefMut};
pub struct StateContainer<S, T>
where
S: StateResolver<T>,
T: Clone,
{
inner: S,
later: Vec<T>,
}
impl<S, T> StateContainer<S, T>
where
S: StateResolver<T>,
T: Clone,
{
pub fn feed(&mut self, input: &T) {
let handle_result = self.inner.feed(input);
if let FeedResult::Later = handle_result {
self.later.push(input.clone());
}
}
pub fn flush(&mut self) {
let queued = mem::take(&mut self.later);
for item in queued {
if let FeedResult::Later = self.inner.feed(&item) {
self.later.push(item);
}
}
self.inner.flush_inner();
}
}
impl<S, T> Deref for StateContainer<S, T>
where
S: StateResolver<T>,
T: Clone,
{
type Target = S;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<S, T> DerefMut for StateContainer<S, T>
where
S: StateResolver<T>,
T: Clone,
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl<S, T> Default for StateContainer<S, T>
where
S: StateResolver<T> + Default,
T: Clone,
{
fn default() -> Self {
StateContainer {
inner: S::default(),
later: Vec::new(),
}
}
}
impl<S, T> Serialize for StateContainer<S, T>
where
S: StateResolver<T> + Serialize,
T: Clone,
{
fn serialize<Se>(&self, serializer: Se) -> Result<Se::Ok, Se::Error>
where
Se: Serializer,
{
self.inner.serialize(serializer)
}
}
impl<'de, S, T> Deserialize<'de> for StateContainer<S, T>
where
S: StateResolver<T> + Deserialize<'de>,
T: Clone,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(StateContainer {
inner: S::deserialize(deserializer)?,
later: Vec::new(),
})
}
}
impl<S, T> From<S> for StateContainer<S, T>
where
S: StateResolver<T>,
T: Clone,
{
fn from(value: S) -> Self {
StateContainer {
inner: value,
later: Vec::new(),
}
}
}
impl<S, T> Debug for StateContainer<S, T>
where
S: StateResolver<T> + Debug,
T: Clone,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.inner, f)
}
}