use alloc::vec::Vec;
use crate::storage::{Heap, Storage};
use crate::{ActivityId, Error, StateImpact, StateTimeline, StateValue, Tick, Window};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FlexibleState<'a> {
pub activity: ActivityId,
pub window: Window,
pub impacts: &'a [StateImpact],
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StateVerdict {
Safe,
Possible(StateEnvelopeViolation),
Certain(StateEnvelopeViolation),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StateEnvelopeViolation {
Mismatch {
at: Tick,
required: StateValue,
requirer: ActivityId,
},
Conflict {
at: Tick,
setters: Vec<ActivityId>,
},
}
impl StateEnvelopeViolation {
#[must_use]
pub const fn at(&self) -> Tick {
match *self {
Self::Mismatch { at, .. } | Self::Conflict { at, .. } => at,
}
}
}
#[derive(Debug, Clone)]
pub struct StateEnvelope<'a, S: Storage = Heap> {
timeline: &'a StateTimeline<S>,
entities: Vec<Entity>,
}
type SetEntry = (Tick, StateValue, ActivityId);
#[derive(Debug, Clone)]
struct Entity {
window: Window,
sets: Vec<SetEntry>,
requires: Vec<(ActivityId, Tick, Tick, StateValue)>,
}
#[derive(Debug, Clone, Copy)]
struct Opt<'a> {
lo: i128,
hi: i128,
sets: &'a [SetEntry],
}
impl Opt<'_> {
fn differs_from(&self, value: StateValue) -> bool {
self.sets.iter().any(|&(_, other, _)| other != value)
}
fn is_only(&self, value: StateValue) -> bool {
!self.differs_from(value)
}
}
#[derive(Debug, Clone, Default)]
struct Options<'a> {
none: bool,
options: Vec<Opt<'a>>,
}
impl Options<'_> {
fn can_be_at_most(&self, x: i128) -> bool {
self.none || self.options.iter().any(|option| option.lo <= x)
}
fn can_yield_to(&self, x: i128, value: StateValue) -> bool {
self.none
|| self.options.iter().any(|option| {
option.lo < x || (option.is_only(value) && option.lo <= x && x <= option.hi)
})
}
}
#[derive(Debug, Clone, Copy)]
struct Need {
entity: usize,
activity: ActivityId,
start: Tick,
end: Tick,
value: StateValue,
}
#[derive(Debug, Clone, Copy)]
struct Piece<'a> {
first: i128,
last: i128,
own: Option<(Tick, &'a [SetEntry])>,
}
impl<'a, S: Storage> StateEnvelope<'a, S> {
pub fn new(
timeline: &'a StateTimeline<S>,
flexible: &'a [FlexibleState<'a>],
) -> Result<Self, Error> {
for activity in flexible {
for impact in activity.impacts {
for start in [activity.window.earliest(), activity.window.latest()] {
timeline.validate(impact.shifted(start).ok_or(Error::Overflow)?)?;
}
}
}
let mut entities = Vec::new();
entities
.try_reserve_exact(flexible.len() + 1)
.map_err(|_| Error::OutOfMemory)?;
let fixed = timeline.impacts().iter().copied();
entities.push(entity(Window::at(0), fixed)?);
for activity in flexible {
let impacts = activity
.impacts
.iter()
.map(|&impact| (activity.activity, impact));
entities.push(entity(activity.window, impacts)?);
}
Ok(Self { timeline, entities })
}
pub fn check(&self) -> Result<StateVerdict, Error> {
let (possible_conflict, certain_conflict) = self.conflicts()?;
let (possible_mismatch, certain_mismatch) = self.mismatches()?;
let certain = earliest(certain_conflict, certain_mismatch);
if let Some(violation) = certain {
return Ok(StateVerdict::Certain(violation));
}
Ok(earliest(possible_conflict, possible_mismatch)
.map_or(StateVerdict::Safe, StateVerdict::Possible))
}
#[must_use]
pub const fn timeline(&self) -> &StateTimeline<S> {
self.timeline
}
fn conflicts(
&self,
) -> Result<
(
Option<StateEnvelopeViolation>,
Option<StateEnvelopeViolation>,
),
Error,
> {
let mut possible: Option<Tick> = None;
let mut certain: Option<Tick> = None;
let sets = self.set_ranges();
for (index, a) in sets.clone().enumerate() {
for b in sets.clone().skip(index + 1) {
if a.value == b.value {
continue;
}
let coupled = a.entity == b.entity;
if coupled && a.offset != b.offset {
continue;
}
let meet = if coupled { Some(a.lo) } else { a.meet(&b) };
if let Some(at) = meet {
possible = Some(possible.map_or(at, |p| p.min(at)));
}
if a.lo == a.hi && b.lo == b.hi && a.lo == b.lo {
certain = Some(certain.map_or(a.lo, |c| c.min(a.lo)));
}
}
}
let explain = |at: Option<Tick>| -> Result<Option<StateEnvelopeViolation>, Error> {
at.map(|at| self.conflict_at(at)).transpose()
};
Ok((explain(possible)?, explain(certain)?))
}
fn set_ranges(&self) -> impl Iterator<Item = SetRange> + Clone + '_ {
self.entities.iter().enumerate().flat_map(|(entity, e)| {
e.sets
.iter()
.map(move |&(offset, value, activity)| SetRange {
entity,
offset,
value,
activity,
lo: e.window.earliest() + offset,
hi: e.window.latest() + offset,
})
})
}
fn conflict_at(&self, at: Tick) -> Result<StateEnvelopeViolation, Error> {
let mut setters = Vec::new();
for set in self.set_ranges().filter(|set| set.lo <= at && at <= set.hi) {
setters.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
setters.push(set.activity);
}
setters.sort_unstable();
setters.dedup();
Ok(StateEnvelopeViolation::Conflict { at, setters })
}
fn mismatches(
&self,
) -> Result<
(
Option<StateEnvelopeViolation>,
Option<StateEnvelopeViolation>,
),
Error,
> {
let needs: Vec<Need> = self.needs().collect();
let mut possible: Option<(Tick, ActivityId, StateValue)> = None;
let mut certain: Option<(Tick, ActivityId, StateValue)> = None;
let Some((from, to)) = self.coverage(&needs) else {
return Ok((None, None));
};
let settled = self.settled();
for t in self.candidate_ticks(&needs, from, to)? {
if possible.is_some_and(|p| p.0 < t) && certain.is_some() {
break;
}
let options = self.options_at(t)?;
let relevant =
|need: &&Need| self.may_cover(need, t) && t <= self.last_tick(need, settled);
for need in needs.iter().filter(relevant) {
let key = (t, need.activity, need.value);
if possible.is_none_or(|p| key < p) && self.possibly_broken(need, t, &options)? {
possible = Some(key);
}
if certain.is_none_or(|c| key < c) && self.certainly_broken(need, t, &options)? {
certain = Some(key);
}
}
}
let explain = |found: Option<(Tick, ActivityId, StateValue)>| {
found.map(
|(at, requirer, required)| StateEnvelopeViolation::Mismatch {
at,
required,
requirer,
},
)
};
Ok((explain(possible), explain(certain)))
}
fn needs(&self) -> impl Iterator<Item = Need> + '_ {
self.entities.iter().enumerate().flat_map(|(entity, e)| {
e.requires
.iter()
.map(move |&(activity, start, end, value)| Need {
entity,
activity,
start,
end,
value,
})
})
}
fn coverage(&self, needs: &[Need]) -> Option<(Tick, Tick)> {
let settled = self.settled();
let from = needs
.iter()
.map(|need| self.starts(need.entity).earliest() + need.start);
let to = needs.iter().map(|need| self.last_tick(need, settled));
Some((from.min()?, to.max()?))
}
fn candidate_ticks(&self, needs: &[Need], from: Tick, to: Tick) -> Result<Vec<Tick>, Error> {
let mut constants: Vec<i128> = Vec::new();
let mut shifts: Vec<i128> = Vec::new();
for (index, entity) in self.entities.iter().enumerate() {
let mut offsets: Vec<i128> = Vec::new();
offsets.push(0);
offsets.extend(entity.sets.iter().map(|&(offset, _, _)| i128::from(offset)));
for need in needs.iter().filter(|need| need.entity == index) {
offsets.extend([i128::from(need.start), i128::from(need.end)]);
}
offsets.sort_unstable();
offsets.dedup();
let (lo, hi) = (
i128::from(entity.window.earliest()),
i128::from(entity.window.latest()),
);
constants.extend(
offsets
.iter()
.flat_map(|&offset| [lo + offset, hi + offset]),
);
for &p in &offsets {
shifts.extend(offsets.iter().map(|&q| p - q));
}
}
constants.sort_unstable();
constants.dedup();
shifts.sort_unstable();
shifts.dedup();
let (from_wide, to_wide) = (i128::from(from), i128::from(to));
let mut ticks: Vec<Tick> = Vec::new();
let mut push = |tick: i128| -> Result<(), Error> {
if from_wide <= tick && tick <= to_wide {
ticks.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
ticks.push(Tick::try_from(tick).map_err(|_| Error::Overflow)?);
}
Ok(())
};
for need in needs {
push(i128::from(self.starts(need.entity).earliest()) + i128::from(need.start))?;
}
for &constant in &constants {
for &shift in &shifts {
for nudge in -2..=2 {
push(constant - shift + nudge)?;
}
}
}
ticks.sort_unstable();
ticks.dedup();
Ok(ticks)
}
fn settled(&self) -> Option<Tick> {
self.set_ranges().map(|set| set.hi).max()
}
fn last_tick(&self, need: &Need, settled: Option<Tick>) -> Tick {
let window = self.starts(need.entity);
let covered_end = i128::from(window.latest()) + i128::from(need.end) - 1;
let fully_covered = i128::from(window.latest()) + i128::from(need.start);
let settled = settled.map_or(i128::MIN, i128::from);
let last = covered_end.min(settled.max(fully_covered) + 1);
Tick::try_from(last).unwrap_or(Tick::MAX)
}
fn starts(&self, index: usize) -> Window {
self.entities[index].window
}
fn may_cover(&self, need: &Need, t: Tick) -> bool {
self.covering_starts(need, t).is_some()
}
fn covering_starts(&self, need: &Need, t: Tick) -> Option<(i128, i128)> {
let window = self.starts(need.entity);
let t = i128::from(t);
let first = i128::from(window.earliest()).max(t - i128::from(need.end) + 1);
let last = i128::from(window.latest()).min(t - i128::from(need.start));
(first <= last).then_some((first, last))
}
fn options_at(&self, t: Tick) -> Result<Vec<Options<'_>>, Error> {
let mut all = Vec::new();
all.try_reserve_exact(self.entities.len())
.map_err(|_| Error::OutOfMemory)?;
for entity in &self.entities {
all.push(entity.options_at(t)?);
}
Ok(all)
}
fn possibly_broken(
&self,
need: &Need,
t: Tick,
options: &[Options<'_>],
) -> Result<bool, Error> {
let Some(starts) = self.covering_starts(need, t) else {
return Ok(false);
};
let others = |x: i128, skip: Option<usize>| {
options.iter().enumerate().all(|(index, other)| {
index == need.entity || Some(index) == skip || other.can_be_at_most(x)
})
};
for piece in self.entities[need.entity].pieces(t, starts)? {
let own_tick = piece
.own
.map(|(offset, _)| piece.first + i128::from(offset));
if let Some((offset, sets)) = piece.own {
let latest = piece.last + i128::from(offset);
let own = Opt {
lo: latest,
hi: latest,
sets,
};
if own.differs_from(need.value) && others(latest, None) {
return Ok(true);
}
}
for (index, other) in options.iter().enumerate() {
if index == need.entity {
continue;
}
for option in other.options.iter().filter(|o| o.differs_from(need.value)) {
let own_fits = own_tick.is_none_or(|own| own <= option.hi);
if own_fits && others(option.hi, Some(index)) {
return Ok(true);
}
}
}
let all_none = options
.iter()
.enumerate()
.all(|(index, other)| index == need.entity || other.none);
if piece.own.is_none() && all_none && self.timeline.initial() != need.value {
return Ok(true);
}
}
Ok(false)
}
fn certainly_broken(
&self,
need: &Need,
t: Tick,
options: &[Options<'_>],
) -> Result<bool, Error> {
let window = self.starts(need.entity);
let starts = (i128::from(window.earliest()), i128::from(window.latest()));
if self.covering_starts(need, t) != Some(starts) {
return Ok(false);
}
let value = need.value;
let others = |x: i128, skip: Option<usize>| {
options.iter().enumerate().all(|(index, other)| {
index == need.entity || Some(index) == skip || other.can_yield_to(x, value)
})
};
for piece in self.entities[need.entity].pieces(t, starts)? {
if let Some((offset, sets)) = piece.own {
let latest = piece.last + i128::from(offset);
let own = Opt {
lo: latest,
hi: latest,
sets,
};
if own.is_only(value) && others(latest, None) {
return Ok(false);
}
}
for (index, other) in options.iter().enumerate() {
if index == need.entity {
continue;
}
for option in other.options.iter().filter(|o| o.is_only(value)) {
if piece_yields(&piece, option.hi, value) && others(option.hi, Some(index)) {
return Ok(false);
}
}
}
let all_none = options
.iter()
.enumerate()
.all(|(index, other)| index == need.entity || other.none);
if piece.own.is_none() && all_none && self.timeline.initial() == value {
return Ok(false);
}
}
Ok(true)
}
}
fn piece_yields(piece: &Piece<'_>, x: i128, value: StateValue) -> bool {
let Some((offset, sets)) = piece.own else {
return true;
};
let offset = i128::from(offset);
let before = piece.first + offset < x;
let tie = (piece.first..=piece.last).contains(&(x - offset))
&& sets.iter().all(|&(_, other, _)| other == value);
before || tie
}
#[derive(Debug, Clone, Copy)]
struct SetRange {
entity: usize,
offset: Tick,
value: StateValue,
activity: ActivityId,
lo: Tick,
hi: Tick,
}
impl SetRange {
fn meet(&self, other: &Self) -> Option<Tick> {
let lo = self.lo.max(other.lo);
(lo <= self.hi.min(other.hi)).then_some(lo)
}
}
impl Entity {
fn options_at(&self, t: Tick) -> Result<Options<'_>, Error> {
let t = i128::from(t);
let (lo, hi) = (
i128::from(self.window.earliest()),
i128::from(self.window.latest()),
);
let mut options = Vec::new();
let groups = self.groups();
let none = groups
.first()
.is_none_or(|&(offset, _)| hi + i128::from(offset) > t);
for (index, &(offset, sets)) in groups.iter().enumerate() {
let offset = i128::from(offset);
let after = groups
.get(index + 1)
.map_or(lo, |&(next, _)| t - i128::from(next) + 1);
let first = lo.max(after);
let last = hi.min(t - offset);
if first <= last {
options.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
options.push(Opt {
lo: first + offset,
hi: last + offset,
sets,
});
}
}
Ok(Options { none, options })
}
fn groups(&self) -> Vec<(Tick, &[SetEntry])> {
let mut groups = Vec::new();
let mut rest = self.sets.as_slice();
while let Some(&(offset, _, _)) = rest.first() {
let count = rest.iter().take_while(|set| set.0 == offset).count();
let (now, later) = rest.split_at(count);
groups.push((offset, now));
rest = later;
}
groups
}
fn pieces(&self, t: Tick, (first, last): (i128, i128)) -> Result<Vec<Piece<'_>>, Error> {
let t = i128::from(t);
let groups = self.groups();
let mut pieces = Vec::new();
pieces
.try_reserve(groups.len() + 1)
.map_err(|_| Error::OutOfMemory)?;
let none_from = groups
.first()
.map_or(first, |&(offset, _)| first.max(t - i128::from(offset) + 1));
if none_from <= last {
pieces.push(Piece {
first: none_from,
last,
own: None,
});
}
for (index, &(offset, sets)) in groups.iter().enumerate() {
let from = groups
.get(index + 1)
.map_or(first, |&(next, _)| first.max(t - i128::from(next) + 1));
let to = last.min(t - i128::from(offset));
if from <= to {
pieces.push(Piece {
first: from,
last: to,
own: Some((offset, sets)),
});
}
}
Ok(pieces)
}
}
fn entity(
window: Window,
impacts: impl Iterator<Item = (ActivityId, StateImpact)>,
) -> Result<Entity, Error> {
let mut entity = Entity {
window,
sets: Vec::new(),
requires: Vec::new(),
};
for (activity, impact) in impacts {
match impact {
StateImpact::Set { at, value } => {
entity.sets.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
entity.sets.push((at, value, activity));
}
StateImpact::Require { start, end, value } => {
entity
.requires
.try_reserve(1)
.map_err(|_| Error::OutOfMemory)?;
entity.requires.push((activity, start, end, value));
}
}
}
entity.sets.sort_unstable();
Ok(entity)
}
fn earliest(
conflict: Option<StateEnvelopeViolation>,
mismatch: Option<StateEnvelopeViolation>,
) -> Option<StateEnvelopeViolation> {
match (conflict, mismatch) {
(Some(conflict), Some(mismatch)) if mismatch.at() < conflict.at() => Some(mismatch),
(Some(conflict), _) => Some(conflict),
(None, mismatch) => mismatch,
}
}