pub(crate) mod extract;
pub(crate) mod profile;
pub(crate) mod sweep;
#[cfg(feature = "alloc")]
use crate::storage::Heap;
use crate::storage::{Seq, Slot, Storage};
use crate::{ActivityId, Container, Error, Impact, Level, Target, Tick, Violation};
use profile::{Point, Profile};
use sweep::{Breach, Frame};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Bounds {
min: Level,
max: Level,
}
impl Bounds {
pub const fn new(min: Level, max: Level) -> Result<Self, Error> {
if min > max {
return Err(Error::InvalidBounds { min, max });
}
Ok(Self { min, max })
}
#[must_use]
pub const fn min(&self) -> Level {
self.min
}
#[must_use]
pub const fn max(&self) -> Level {
self.max
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Kind {
Depletable,
Claimable,
}
#[cfg_attr(feature = "alloc", doc = "[`depletable`]: Self::depletable")]
#[cfg_attr(not(feature = "alloc"), doc = "[`depletable`]: crate#features")]
#[cfg_attr(feature = "alloc", doc = "[`claimable`]: Self::claimable")]
#[cfg_attr(not(feature = "alloc"), doc = "[`claimable`]: crate#features")]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Timeline<
#[cfg(feature = "alloc")] S: Storage = Heap,
#[cfg(not(feature = "alloc"))] S: Storage,
> {
kind: Kind,
start: Tick,
initial: Level,
bounds: Bounds,
budget: usize,
impacts: S::List<(ActivityId, Impact)>,
profile: Profile<S>,
targets: S::List<Target>,
}
#[cfg(feature = "alloc")]
impl Timeline {
pub const fn depletable(
start: Tick,
initial: Level,
bounds: Bounds,
budget: usize,
) -> Result<Self, Error> {
Self::depletable_in(start, initial, bounds, budget)
}
pub const fn claimable(start: Tick, capacity: Level, budget: usize) -> Result<Self, Error> {
Self::claimable_in(start, capacity, budget)
}
}
impl<S: Storage> Timeline<S> {
#[cfg_attr(
feature = "alloc",
doc = "[`Timeline::depletable`]: Timeline::depletable"
)]
#[cfg_attr(
not(feature = "alloc"),
doc = "[`Timeline::depletable`]: crate#features"
)]
pub const fn depletable_in(
start: Tick,
initial: Level,
bounds: Bounds,
budget: usize,
) -> Result<Self, Error> {
Ok(Self::new(Kind::Depletable, start, initial, bounds, budget))
}
#[cfg_attr(
feature = "alloc",
doc = "[`Timeline::claimable`]: Timeline::claimable"
)]
#[cfg_attr(
not(feature = "alloc"),
doc = "[`Timeline::claimable`]: crate#features"
)]
pub const fn claimable_in(start: Tick, capacity: Level, budget: usize) -> Result<Self, Error> {
match Bounds::new(0, capacity) {
Ok(bounds) => Ok(Self::new(Kind::Claimable, start, capacity, bounds, budget)),
Err(error) => Err(error),
}
}
const fn new(kind: Kind, start: Tick, initial: Level, bounds: Bounds, budget: usize) -> Self {
Self {
kind,
start,
initial,
bounds,
budget,
impacts: <S::List<(ActivityId, Impact)> as Seq<_>>::EMPTY,
profile: Profile::EMPTY,
targets: <S::List<Target> as Seq<_>>::EMPTY,
}
}
#[must_use]
pub const fn kind(&self) -> Kind {
self.kind
}
#[must_use]
pub const fn start(&self) -> Tick {
self.start
}
#[must_use]
pub const fn initial(&self) -> Level {
self.initial
}
#[must_use]
pub const fn bounds(&self) -> Bounds {
self.bounds
}
#[must_use]
pub const fn budget(&self) -> usize {
self.budget
}
#[must_use]
pub fn impacts(&self) -> &[(ActivityId, Impact)] {
&self.impacts
}
pub fn add(&mut self, activity: ActivityId, impact: Impact) -> Result<(), Error> {
self.validate(impact)?;
self.ensure_room(1)?;
self.impacts.try_reserve(1, Container::Impacts)?;
self.profile.add(&impact)?;
self.impacts
.try_push((activity, impact), Container::Impacts)
}
pub fn remove(&mut self, activity: ActivityId) -> usize {
let before = self.impacts.len();
let profile = &mut self.profile;
self.impacts.retain(|&(owner, impact)| {
let keep = owner != activity;
if !keep {
profile.remove(&impact);
}
keep
});
before - self.impacts.len()
}
pub fn add_target(&mut self, target: Target) -> Result<(), Error> {
if target.at < self.start {
return Err(Error::BeforeStart {
at: target.at,
start: self.start,
});
}
let index = self
.targets
.partition_point(|other| other.key() <= target.key());
self.targets.try_insert(index, target, Container::Targets)
}
#[must_use]
pub fn targets(&self) -> &[Target] {
&self.targets
}
pub fn remove_targets_at(&mut self, at: Tick) -> usize {
let before = self.targets.len();
self.targets.retain(|target| target.at != at);
before - self.targets.len()
}
pub(crate) fn undo_last(&mut self) {
if let Some((_, impact)) = self.impacts.pop() {
self.profile.remove(&impact);
}
}
#[cfg(feature = "alloc")]
pub(crate) fn change_ticks(&self) -> impl Iterator<Item = Tick> + '_ {
let points = self.profile.points().iter().map(|point| point.at);
points.chain(self.targets.iter().map(|target| target.at))
}
pub(crate) fn first_change_from(&self, x: i128) -> Option<Tick> {
let points = self.profile.points();
let point = points.get(points.partition_point(|point| i128::from(point.at) < x));
let target = self.targets.get(
self.targets
.partition_point(|target| i128::from(target.at) < x),
);
let start = (i128::from(self.start) >= x).then_some(self.start);
[
start,
point.map(|point| point.at),
target.map(|target| target.at),
]
.into_iter()
.flatten()
.min()
}
pub(crate) fn ensure_room(&self, extra: usize) -> Result<(), Error> {
let needed = self.impacts.len().saturating_add(extra);
if needed > self.budget {
return Err(Error::BudgetExhausted { limit: self.budget });
}
match self.impacts.capacity() {
Some(capacity) if needed > capacity => Err(Error::CapacityExceeded {
container: Container::Impacts,
capacity,
}),
_ => Ok(()),
}
}
pub(crate) fn validate(&self, impact: Impact) -> Result<(), Error> {
if self.kind == Kind::Claimable && !matches!(impact, Impact::Claim { .. }) {
return Err(Error::KindMismatch);
}
match impact {
Impact::Claim { start, end, amount } => {
if end <= start {
return Err(Error::EmptyInterval { start, end });
}
if amount <= 0 {
return Err(Error::NonPositiveAmount { amount });
}
}
Impact::Rate { start, end, .. } if end <= start => {
return Err(Error::EmptyInterval { start, end });
}
Impact::Step { .. } | Impact::Rate { .. } => {}
}
let at = impact.first_tick();
if at < self.start {
return Err(Error::BeforeStart {
at,
start: self.start,
});
}
Ok(())
}
pub fn level_at(&self, t: Tick) -> Result<Level, Error> {
if t < self.start {
return Err(Error::BeforeStart {
at: t,
start: self.start,
});
}
let level = self
.impacts
.iter()
.try_fold(i128::from(self.initial), |level, (_, impact)| {
level.checked_add(impact.contribution_at(t)?)
})
.ok_or(Error::Overflow)?;
Level::try_from(level).map_err(|_| Error::Overflow)
}
#[must_use]
pub fn has_rates(&self) -> bool {
self.profile.has_slope()
}
pub fn first_violation(&self) -> Result<Option<Violation<S>>, Error> {
match self.breach_with(&[])? {
Some(breach) => sweep::explain::<S>(&self.impacts, breach).map(Some),
None => Ok(None),
}
}
#[cfg(feature = "alloc")]
pub(crate) fn contributors_at(
&self,
t: Tick,
bound: crate::Bound,
) -> Result<S::List<ActivityId>, Error> {
sweep::contributors::<S>(&self.impacts, t, bound)
}
pub(crate) fn narrow(
&self,
first: &[Point],
second: &[Point],
offsets: &mut crate::plan::Offsets,
) -> Result<(), Error> {
let frame = self.frame();
sweep::narrow(&frame, self.profile.points(), [first, second], offsets)
}
fn frame(&self) -> Frame<'_> {
Frame {
start: self.start,
initial: self.initial,
bounds: self.bounds,
targets: &self.targets,
}
}
pub(crate) fn breach_with(&self, extra: &[Point]) -> Result<Option<Breach>, Error> {
sweep::first_breach(&self.frame(), self.profile.points(), extra)
}
}
impl<S: Storage> crate::storage::Sealed for Timeline<S> {}
impl<S: Storage> Slot for Timeline<S> {
const EMPTY: Self = Self::new(Kind::Depletable, 0, 0, Bounds { min: 0, max: 0 }, 0);
}