use crate::storage::{Seq, Slot, Storage};
use crate::{Container, Error, Impact, Tick};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct Point {
pub(crate) at: Tick,
pub(crate) step: i128,
pub(crate) slope: i128,
pub(crate) refs: usize,
}
impl Point {
pub(crate) const fn loose(at: Tick, step: i128, slope: i128) -> Self {
Self {
at,
step,
slope,
refs: 0,
}
}
pub(crate) const fn is_empty(&self) -> bool {
self.step == 0 && self.slope == 0
}
}
impl crate::storage::Sealed for Point {}
impl Slot for Point {
const EMPTY: Self = Self::loose(0, 0, 0);
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct Profile<S: Storage> {
pub(super) points: S::DoubleList<Point>,
}
impl<S: Storage> Profile<S> {
pub(crate) const EMPTY: Self = Self {
points: <S::DoubleList<Point> as Seq<Point>>::EMPTY,
};
pub(crate) fn points(&self) -> &[Point] {
&self.points
}
pub(crate) fn add(&mut self, impact: &Impact) -> Result<(), Error> {
self.points.try_reserve(2, Container::ChangePoints)?;
for (at, step, slope) in impact.changes().into_iter().flatten() {
match self.points.binary_search_by_key(&at, |point| point.at) {
Ok(index) => {
let point = &mut self.points[index];
point.step += step;
point.slope += slope;
point.refs += 1;
}
Err(index) => {
let point = Point {
refs: 1,
..Point::loose(at, step, slope)
};
self.points
.try_insert(index, point, Container::ChangePoints)?;
}
}
}
Ok(())
}
pub(crate) fn remove(&mut self, impact: &Impact) {
for (at, step, slope) in impact.changes().into_iter().flatten() {
let Ok(index) = self.points.binary_search_by_key(&at, |point| point.at) else {
debug_assert!(false, "removed impact was never added");
continue;
};
let point = &mut self.points[index];
point.step -= step;
point.slope -= slope;
point.refs -= 1;
if point.refs == 0 {
debug_assert!(
point.is_empty(),
"unreferenced point still changes the level"
);
self.points.remove(index);
}
}
}
pub(crate) fn has_slope(&self) -> bool {
self.points.iter().any(|point| point.slope != 0)
}
}