use alloc::vec::Vec;
use core::fmt::Debug;
use fluxion_core::{HasTimestamp, Timestamped};
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct WithPrevious<T> {
pub previous: Option<T>,
pub current: T,
}
impl<T> WithPrevious<T> {
pub fn new(previous: Option<T>, current: T) -> Self {
Self { previous, current }
}
pub fn has_previous(&self) -> bool {
self.previous.is_some()
}
pub fn as_pair(&self) -> Option<(&T, &T)> {
self.previous.as_ref().map(|prev| (prev, &self.current))
}
}
impl<T: Timestamped> HasTimestamp for WithPrevious<T> {
type Timestamp = T::Timestamp;
fn timestamp(&self) -> Self::Timestamp {
self.current.timestamp()
}
}
impl<T: Timestamped> Timestamped for WithPrevious<T> {
type Inner = T::Inner;
fn with_timestamp(value: Self::Inner, timestamp: Self::Timestamp) -> Self {
Self {
previous: None,
current: T::with_timestamp(value, timestamp),
}
}
fn into_inner(self) -> Self::Inner {
self.current.into_inner()
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct CombinedState<V, TS = u64>
where
V: Clone + Debug + Ord,
TS: Clone + Debug + Ord,
{
state: Vec<(V, TS)>,
timestamp: TS,
}
impl<V, TS> CombinedState<V, TS>
where
V: Clone + Debug + Ord,
TS: Clone + Debug + Ord,
{
pub fn new(state: Vec<(V, TS)>, timestamp: TS) -> Self {
Self { state, timestamp }
}
pub fn values(&self) -> Vec<V> {
self.state.iter().map(|(v, _)| v.clone()).collect()
}
pub fn timestamps(&self) -> Vec<TS> {
self.state.iter().map(|(_, ts)| ts.clone()).collect()
}
pub fn pairs(&self) -> &[(V, TS)] {
&self.state
}
pub fn len(&self) -> usize {
self.state.len()
}
pub fn is_empty(&self) -> bool {
self.state.is_empty()
}
}
impl<V, TS> HasTimestamp for CombinedState<V, TS>
where
V: Clone + Debug + Ord,
TS: Clone + Debug + Ord + Copy + Send + Sync,
{
type Timestamp = TS;
fn timestamp(&self) -> Self::Timestamp {
self.timestamp
}
}
impl<V, TS> Timestamped for CombinedState<V, TS>
where
V: Clone + Debug + Ord,
TS: Clone + Debug + Ord + Copy + Send + Sync,
{
type Inner = Self;
fn with_timestamp(value: Self::Inner, timestamp: Self::Timestamp) -> Self {
Self {
state: value.state,
timestamp,
}
}
fn into_inner(self) -> Self::Inner {
self
}
}