use crate::{ActivityId, Error, Impact, Level, Tick, Window};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Anchor {
Start(Tick),
End(Tick),
}
impl Anchor {
#[must_use]
pub const fn resolve(self, duration: Tick) -> Option<Tick> {
match self {
Self::Start(offset) => Some(offset),
Self::End(offset) => duration.checked_add(offset),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Uncertain {
Step {
at: Anchor,
delta: Level,
},
Claim {
start: Anchor,
end: Anchor,
amount: Level,
},
Rate {
start: Anchor,
end: Anchor,
per_tick: Level,
},
}
impl Uncertain {
#[must_use]
pub const fn resolve(&self, duration: Tick) -> Option<Impact> {
match *self {
Self::Step { at, delta } => match at.resolve(duration) {
Some(at) => Some(Impact::Step { at, delta }),
None => None,
},
Self::Claim { start, end, amount } => {
match (start.resolve(duration), end.resolve(duration)) {
(Some(start), Some(end)) => Some(Impact::Claim { start, end, amount }),
_ => None,
}
}
Self::Rate {
start,
end,
per_tick,
} => match (start.resolve(duration), end.resolve(duration)) {
(Some(start), Some(end)) => Some(Impact::Rate {
start,
end,
per_tick,
}),
_ => None,
},
}
}
pub(super) const fn anchors(&self) -> [Anchor; 2] {
match *self {
Self::Step { at, .. } => [at, at],
Self::Claim { start, end, .. } | Self::Rate { start, end, .. } => [start, end],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Contingent<'a> {
pub activity: ActivityId,
pub window: Window,
pub duration: Window,
pub impacts: &'a [Uncertain],
}
pub(super) fn widened(impact: Impact) -> Result<Impact, Error> {
let widen = |start: Tick, end: Tick| -> Result<Tick, Error> {
match end.cmp(&start) {
core::cmp::Ordering::Less => Err(Error::EmptyInterval { start, end }),
core::cmp::Ordering::Equal => start.checked_add(1).ok_or(Error::Overflow),
core::cmp::Ordering::Greater => Ok(end),
}
};
Ok(match impact {
Impact::Step { .. } => impact,
Impact::Claim { start, end, amount } => Impact::Claim {
start,
end: widen(start, end)?,
amount,
},
Impact::Rate {
start,
end,
per_tick,
} => Impact::Rate {
start,
end: widen(start, end)?,
per_tick,
},
})
}