use super::contingent::{Anchor, Uncertain};
use crate::{ActivityId, Error, Impact, Tick, Window};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Extreme {
Lower,
Upper,
}
impl Extreme {
const fn pick(self, a: i128, b: i128) -> i128 {
match self {
Self::Lower if b < a => b,
Self::Upper if b > a => b,
Self::Lower | Self::Upper => a,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Shape<'a> {
Fixed(&'a [Impact]),
Uncertain {
duration: Window,
impacts: &'a [Uncertain],
},
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Member<'a> {
pub(crate) activity: ActivityId,
pub(crate) window: Window,
pub(crate) shape: Shape<'a>,
}
impl Member<'_> {
pub(crate) const fn duration(&self) -> Window {
match self.shape {
Shape::Fixed(_) => Window::at(0),
Shape::Uncertain { duration, .. } => duration,
}
}
pub(crate) fn is_stepwise(&self) -> bool {
match self.shape {
Shape::Fixed(impacts) => !impacts.iter().any(Impact::is_rate),
Shape::Uncertain { .. } => false,
}
}
pub(crate) fn span(&self) -> Tick {
match self.shape {
Shape::Fixed(impacts) => impacts.iter().map(Impact::last_tick).fold(0, Tick::max),
Shape::Uncertain { .. } => 0,
}
}
pub(crate) fn anchored(&self) -> impl Iterator<Item = Uncertain> + '_ {
let (fixed, uncertain): (&[Impact], &[Uncertain]) = match self.shape {
Shape::Fixed(impacts) => (impacts, &[]),
Shape::Uncertain { impacts, .. } => (&[], impacts),
};
let fixed = fixed.iter().map(|&impact| match impact {
Impact::Step { at, delta } => Uncertain::Step {
at: Anchor::Start(at),
delta,
},
Impact::Claim { start, end, amount } => Uncertain::Claim {
start: Anchor::Start(start),
end: Anchor::Start(end),
amount,
},
Impact::Rate {
start,
end,
per_tick,
} => Uncertain::Rate {
start: Anchor::Start(start),
end: Anchor::Start(end),
per_tick,
},
});
fixed.chain(uncertain.iter().copied())
}
pub(crate) fn anchors(&self) -> impl Iterator<Item = Anchor> + '_ {
let (fixed, uncertain): (&[Impact], &[Uncertain]) = match self.shape {
Shape::Fixed(impacts) => (impacts, &[]),
Shape::Uncertain { impacts, .. } => (&[], impacts),
};
let fixed = fixed.iter().flat_map(|impact| {
[
Anchor::Start(impact.first_tick()),
Anchor::Start(impact.last_tick()),
]
});
fixed.chain(uncertain.iter().flat_map(Uncertain::anchors))
}
pub(crate) fn offsets(&self, duration: Window) -> impl Iterator<Item = i128> + '_ {
self.anchors()
.flat_map(move |anchor| match anchor {
Anchor::Start(offset) => [Some(i128::from(offset)), None],
Anchor::End(offset) => [
Some(i128::from(duration.earliest()) + i128::from(offset)),
Some(i128::from(duration.latest()) + i128::from(offset)),
],
})
.flatten()
}
pub(crate) fn extreme_at(
&self,
window: Window,
duration: Window,
t: Tick,
extreme: Extreme,
) -> Result<i128, Error> {
let first = i128::from(t) - i128::from(window.latest());
let last = i128::from(t) - i128::from(window.earliest());
let (d_lo, d_hi) = (
i128::from(duration.earliest()),
i128::from(duration.latest()),
);
let inner = self
.offsets(duration)
.flat_map(|offset| [offset - 1, offset]);
let mut best: Option<i128> = None;
for u in [first, last].into_iter().chain(inner) {
if u < first || u > last {
continue;
}
for d in self.duration_candidates(u, d_lo, d_hi) {
let value = self.profile_at(u, d)?;
best = Some(best.map_or(value, |best| extreme.pick(best, value)));
}
}
Ok(best.unwrap_or(0))
}
fn duration_candidates(
&self,
u: i128,
d_lo: i128,
d_hi: i128,
) -> impl Iterator<Item = i128> + '_ {
let ends = self.anchors().flat_map(move |anchor| match anchor {
Anchor::Start(_) => [None, None],
Anchor::End(offset) => {
let meet = u - i128::from(offset);
[Some(meet), Some(meet + 1)]
}
});
[Some(d_lo), Some(d_hi)]
.into_iter()
.chain(ends)
.flatten()
.filter(move |&d| d_lo <= d && d <= d_hi)
}
pub(crate) fn profile_at(&self, u: i128, d: i128) -> Result<i128, Error> {
if u < i128::from(Tick::MIN) {
return Ok(0);
}
let u = Tick::try_from(u.min(i128::from(Tick::MAX))).map_err(|_| Error::Overflow)?;
let sum = |sum: i128, impact: Impact| -> Result<i128, Error> {
let contribution = impact.contribution_at(u).ok_or(Error::Overflow)?;
sum.checked_add(contribution).ok_or(Error::Overflow)
};
match self.shape {
Shape::Fixed(impacts) => impacts.iter().copied().try_fold(0, sum),
Shape::Uncertain { impacts, .. } => {
let d = Tick::try_from(d).map_err(|_| Error::Overflow)?;
impacts.iter().try_fold(0, |total, impact| {
sum(total, impact.resolve(d).ok_or(Error::Overflow)?)
})
}
}
}
}