Skip to main content

resource_timeline/envelope/
state.rs

1//! State envelopes: requirements and conflicts over every schedule that start windows admit.
2//!
3//! A [`StateEnvelope`] answers for a [`StateTimeline`] what [`Envelope`](super::Envelope)
4//! answers for a numeric one: given activities whose starts are only known to lie in windows,
5//! can some schedule break a requirement or create contradicting sets, and does every schedule
6//! do so at the same tick?
7//!
8//! # Method
9//!
10//! The windows are independent, so at a tick `t` each activity contributes one of a few
11//! *options*: "its latest own set at or before `t` is the one at offset `o`", available for the
12//! starts that put that set at or before `t` and the next own set after `t`, at ticks
13//! `[lo, hi]`; or "none of its sets yet". The state at `t` is decided by the latest option
14//! chosen. For a requirement of value `v` held by activity `A`:
15//!
16//! - some schedule breaks it at `t` if some option with a value other than `v` can be the
17//!   latest: placed as late as possible, every other activity can stay at or before it;
18//! - every schedule breaks it at `t` if `t` is covered for every start of `A` and no option
19//!   with value `v` can be the unique latest.
20//!
21//! "Certain" is per requirement (and per pair of sets), as "certain" is per bound and tick
22//! for numeric envelopes: two requirements that each fail in half of the schedules make every
23//! schedule fail, yet neither is certain.
24//!
25//! `A`'s own sets move with its start, so its start is split into pieces by its own offsets;
26//! within a piece the best start is its first (to stay early) or its last (to be latest). Two
27//! sets of different values conflict in some schedule if their tick ranges meet, in every
28//! schedule if both ranges are the same single tick. Both answers are exact for independent
29//! windows.
30//!
31//! Every quantity compared is a window end plus an offset, or the tick plus a difference of two
32//! offsets of one activity, so the verdicts can only change near ticks where the two meet.
33//! Requirements are evaluated at those candidate ticks only, `O(f^2 k^3)` of them for `f`
34//! activities with `k` ticks each, at `O(m^2)` per tick for `m` sets; the cost does not grow
35//! with the window lengths or with requirements that last forever.
36
37use alloc::vec::Vec;
38
39use crate::storage::{Heap, Storage};
40use crate::{ActivityId, Error, StateImpact, StateTimeline, StateValue, Tick, Window};
41
42/// An activity with state impacts whose start is only known to lie in a window.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub struct FlexibleState<'a> {
45    /// The activity, reported back in explanations.
46    pub activity: ActivityId,
47    /// The allowed starts.
48    pub window: Window,
49    /// The sets and requirements of the activity, with ticks relative to its start.
50    pub impacts: &'a [StateImpact],
51}
52
53/// The outcome of a state envelope check.
54#[derive(Debug, Clone, PartialEq, Eq, Hash)]
55pub enum StateVerdict {
56    /// Every schedule the windows admit has no state violation.
57    Safe,
58    /// Some schedule has a violation at the reported tick, which is the earliest such tick
59    /// over all schedules. No single requirement and no single pair of sets is broken at one
60    /// tick in every schedule (although every schedule may still be violated, by different
61    /// requirements or at different ticks).
62    Possible(StateEnvelopeViolation),
63    /// One requirement, or one pair of contradicting sets, is broken at the reported tick in
64    /// every schedule; the reported tick is the earliest such tick.
65    Certain(StateEnvelopeViolation),
66}
67
68/// A state violation some or every schedule has at a tick.
69#[derive(Debug, Clone, PartialEq, Eq, Hash)]
70pub enum StateEnvelopeViolation {
71    /// A requirement sees another (or an ambiguous) value.
72    Mismatch {
73        /// The tick.
74        at: Tick,
75        /// The required value.
76        required: StateValue,
77        /// The activity that holds the requirement; the smallest id if several fail at `at`.
78        requirer: ActivityId,
79    },
80    /// Sets of different values may coincide (or always coincide) at the tick.
81    Conflict {
82        /// The tick.
83        at: Tick,
84        /// Every activity with a set that can lie at `at`. Sorted, without duplicates.
85        setters: Vec<ActivityId>,
86    },
87}
88
89impl StateEnvelopeViolation {
90    /// The tick of the violation.
91    #[must_use]
92    pub const fn at(&self) -> Tick {
93        match *self {
94            Self::Mismatch { at, .. } | Self::Conflict { at, .. } => at,
95        }
96    }
97}
98
99/// The state envelope of a state timeline with additional flexible activities.
100///
101/// The timeline's own impacts count as fixed.
102///
103/// # Examples
104///
105/// ```
106/// use resource_timeline::envelope::{FlexibleState, StateEnvelope, StateVerdict};
107/// use resource_timeline::{ActivityId, StateImpact, StateTimeline, Window};
108///
109/// const COLD: u32 = 0;
110/// const WARM: u32 = 1;
111///
112/// // The heater warms the instrument at its start; the analysis needs it warm for 5 ticks.
113/// let instrument = StateTimeline::new(0, COLD, 8);
114/// let heat = [StateImpact::Set { at: 0, value: WARM }];
115/// let analyze = [StateImpact::Require { start: 0, end: 5, value: WARM }];
116/// let flexible = [
117///     FlexibleState { activity: ActivityId(1), window: Window::new(0, 10)?, impacts: &heat },
118///     FlexibleState { activity: ActivityId(2), window: Window::new(10, 20)?, impacts: &analyze },
119/// ];
120/// assert_eq!(StateEnvelope::new(&instrument, &flexible)?.check()?, StateVerdict::Safe);
121///
122/// // If the analysis may start first, some schedule finds the instrument cold.
123/// let early = [flexible[0], FlexibleState { window: Window::new(5, 20)?, ..flexible[1] }];
124/// assert!(matches!(
125///     StateEnvelope::new(&instrument, &early)?.check()?,
126///     StateVerdict::Possible(_)
127/// ));
128/// # Ok::<(), resource_timeline::Error>(())
129/// ```
130#[derive(Debug, Clone)]
131pub struct StateEnvelope<'a, S: Storage = Heap> {
132    /// The timeline with the fixed impacts.
133    timeline: &'a StateTimeline<S>,
134    /// The activities: the fixed impacts first (window `[0, 0]`, absolute ticks), then the
135    /// flexible ones.
136    entities: Vec<Entity>,
137}
138
139/// A stored set: its offset, value and activity.
140type SetEntry = (Tick, StateValue, ActivityId);
141
142/// One independent part of the envelope: the fixed impacts, or one flexible activity.
143#[derive(Debug, Clone)]
144struct Entity {
145    /// The allowed starts.
146    window: Window,
147    /// The sets as `(offset, value, activity)`, sorted by offset.
148    sets: Vec<SetEntry>,
149    /// The requirements as `(activity, start, end, value)`, ticks relative to the start.
150    requires: Vec<(ActivityId, Tick, Tick, StateValue)>,
151}
152
153/// "The latest own set at or before `t` is the one at this offset": the ticks it can take and
154/// the values set there.
155#[derive(Debug, Clone, Copy)]
156struct Opt<'a> {
157    /// The earliest tick of the set for the starts that make it the latest own set.
158    lo: i128,
159    /// The latest such tick.
160    hi: i128,
161    /// The sets at this offset (one entry per set; several values mean a conflict).
162    sets: &'a [SetEntry],
163}
164
165impl Opt<'_> {
166    /// Whether some set here has a value other than `value`.
167    fn differs_from(&self, value: StateValue) -> bool {
168        self.sets.iter().any(|&(_, other, _)| other != value)
169    }
170
171    /// Whether every set here has `value`.
172    fn is_only(&self, value: StateValue) -> bool {
173        !self.differs_from(value)
174    }
175}
176
177/// The options of one entity at a tick.
178#[derive(Debug, Clone, Default)]
179struct Options<'a> {
180    /// Whether some start leaves every own set after the tick.
181    none: bool,
182    /// The available latest-set options.
183    options: Vec<Opt<'a>>,
184}
185
186impl Options<'_> {
187    /// Whether the entity can stay at or before tick `x` (or have no set yet).
188    fn can_be_at_most(&self, x: i128) -> bool {
189        self.none || self.options.iter().any(|option| option.lo <= x)
190    }
191
192    /// Whether the entity can stay strictly before `x`, or tie at `x` with sets of `value` only.
193    fn can_yield_to(&self, x: i128, value: StateValue) -> bool {
194        self.none
195            || self.options.iter().any(|option| {
196                option.lo < x || (option.is_only(value) && option.lo <= x && x <= option.hi)
197            })
198    }
199}
200
201/// A requirement under evaluation: its entity, relative interval and value.
202#[derive(Debug, Clone, Copy)]
203struct Need {
204    /// The entity holding the requirement.
205    entity: usize,
206    /// The activity holding it.
207    activity: ActivityId,
208    /// The first required tick, relative to the start.
209    start: Tick,
210    /// The first tick after the requirement, relative to the start.
211    end: Tick,
212    /// The required value.
213    value: StateValue,
214}
215
216/// One piece of a requirer's starts with the same latest own set at the tick.
217#[derive(Debug, Clone, Copy)]
218struct Piece<'a> {
219    /// The first start of the piece.
220    first: i128,
221    /// The last start of the piece.
222    last: i128,
223    /// The latest own set (offset and sets there), `None` if no own set is due yet.
224    own: Option<(Tick, &'a [SetEntry])>,
225}
226
227impl<'a, S: Storage> StateEnvelope<'a, S> {
228    /// Combines the fixed impacts of `timeline` with the `flexible` activities.
229    ///
230    /// # Errors
231    ///
232    /// - The validation errors of [`StateTimeline::add`] for any flexible impact at the
233    ///   earliest or latest start of its window.
234    /// - [`Error::Overflow`] if a shifted tick does not fit a [`Tick`].
235    /// - [`Error::OutOfMemory`] if the activity lists cannot be allocated.
236    pub fn new(
237        timeline: &'a StateTimeline<S>,
238        flexible: &'a [FlexibleState<'a>],
239    ) -> Result<Self, Error> {
240        for activity in flexible {
241            for impact in activity.impacts {
242                for start in [activity.window.earliest(), activity.window.latest()] {
243                    timeline.validate(impact.shifted(start).ok_or(Error::Overflow)?)?;
244                }
245            }
246        }
247
248        let mut entities = Vec::new();
249        entities
250            .try_reserve_exact(flexible.len() + 1)
251            .map_err(|_| Error::OutOfMemory)?;
252        let fixed = timeline.impacts().iter().copied();
253        entities.push(entity(Window::at(0), fixed)?);
254        for activity in flexible {
255            let impacts = activity
256                .impacts
257                .iter()
258                .map(|&impact| (activity.activity, impact));
259            entities.push(entity(activity.window, impacts)?);
260        }
261
262        Ok(Self { timeline, entities })
263    }
264
265    /// Checks every requirement and every pair of sets over all admitted schedules.
266    ///
267    /// A certain violation anywhere takes precedence over possible ones. At the same tick a
268    /// conflict is reported before a mismatch, and among mismatches the smallest requirer.
269    ///
270    /// # Errors
271    ///
272    /// [`Error::OutOfMemory`] if the working memory cannot be allocated.
273    pub fn check(&self) -> Result<StateVerdict, Error> {
274        let (possible_conflict, certain_conflict) = self.conflicts()?;
275        let (possible_mismatch, certain_mismatch) = self.mismatches()?;
276
277        let certain = earliest(certain_conflict, certain_mismatch);
278        if let Some(violation) = certain {
279            return Ok(StateVerdict::Certain(violation));
280        }
281
282        Ok(earliest(possible_conflict, possible_mismatch)
283            .map_or(StateVerdict::Safe, StateVerdict::Possible))
284    }
285
286    /// The timeline the envelope was built on.
287    #[must_use]
288    pub const fn timeline(&self) -> &StateTimeline<S> {
289        self.timeline
290    }
291
292    /// The earliest possible and the earliest certain conflict between two sets.
293    fn conflicts(
294        &self,
295    ) -> Result<
296        (
297            Option<StateEnvelopeViolation>,
298            Option<StateEnvelopeViolation>,
299        ),
300        Error,
301    > {
302        let mut possible: Option<Tick> = None;
303        let mut certain: Option<Tick> = None;
304        let sets = self.set_ranges();
305        for (index, a) in sets.clone().enumerate() {
306            for b in sets.clone().skip(index + 1) {
307                if a.value == b.value {
308                    continue;
309                }
310
311                let coupled = a.entity == b.entity;
312                if coupled && a.offset != b.offset {
313                    continue;
314                }
315
316                let meet = if coupled { Some(a.lo) } else { a.meet(&b) };
317                if let Some(at) = meet {
318                    possible = Some(possible.map_or(at, |p| p.min(at)));
319                }
320
321                if a.lo == a.hi && b.lo == b.hi && a.lo == b.lo {
322                    certain = Some(certain.map_or(a.lo, |c| c.min(a.lo)));
323                }
324            }
325        }
326
327        let explain = |at: Option<Tick>| -> Result<Option<StateEnvelopeViolation>, Error> {
328            at.map(|at| self.conflict_at(at)).transpose()
329        };
330        Ok((explain(possible)?, explain(certain)?))
331    }
332
333    /// Every set with the ticks it can take.
334    fn set_ranges(&self) -> impl Iterator<Item = SetRange> + Clone + '_ {
335        self.entities.iter().enumerate().flat_map(|(entity, e)| {
336            e.sets
337                .iter()
338                .map(move |&(offset, value, activity)| SetRange {
339                    entity,
340                    offset,
341                    value,
342                    activity,
343                    lo: e.window.earliest() + offset,
344                    hi: e.window.latest() + offset,
345                })
346        })
347    }
348
349    /// A conflict at `at`, with every activity whose set can lie there.
350    fn conflict_at(&self, at: Tick) -> Result<StateEnvelopeViolation, Error> {
351        let mut setters = Vec::new();
352        for set in self.set_ranges().filter(|set| set.lo <= at && at <= set.hi) {
353            setters.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
354            setters.push(set.activity);
355        }
356
357        setters.sort_unstable();
358        setters.dedup();
359        Ok(StateEnvelopeViolation::Conflict { at, setters })
360    }
361
362    /// The earliest possible and the earliest certain mismatch of any requirement.
363    fn mismatches(
364        &self,
365    ) -> Result<
366        (
367            Option<StateEnvelopeViolation>,
368            Option<StateEnvelopeViolation>,
369        ),
370        Error,
371    > {
372        let needs: Vec<Need> = self.needs().collect();
373        let mut possible: Option<(Tick, ActivityId, StateValue)> = None;
374        let mut certain: Option<(Tick, ActivityId, StateValue)> = None;
375        let Some((from, to)) = self.coverage(&needs) else {
376            return Ok((None, None));
377        };
378
379        let settled = self.settled();
380        for t in self.candidate_ticks(&needs, from, to)? {
381            if possible.is_some_and(|p| p.0 < t) && certain.is_some() {
382                break;
383            }
384
385            let options = self.options_at(t)?;
386            let relevant =
387                |need: &&Need| self.may_cover(need, t) && t <= self.last_tick(need, settled);
388            for need in needs.iter().filter(relevant) {
389                let key = (t, need.activity, need.value);
390                if possible.is_none_or(|p| key < p) && self.possibly_broken(need, t, &options)? {
391                    possible = Some(key);
392                }
393
394                if certain.is_none_or(|c| key < c) && self.certainly_broken(need, t, &options)? {
395                    certain = Some(key);
396                }
397            }
398        }
399
400        let explain = |found: Option<(Tick, ActivityId, StateValue)>| {
401            found.map(
402                |(at, requirer, required)| StateEnvelopeViolation::Mismatch {
403                    at,
404                    required,
405                    requirer,
406                },
407            )
408        };
409        Ok((explain(possible), explain(certain)))
410    }
411
412    /// Every requirement of every entity.
413    fn needs(&self) -> impl Iterator<Item = Need> + '_ {
414        self.entities.iter().enumerate().flat_map(|(entity, e)| {
415            e.requires
416                .iter()
417                .map(move |&(activity, start, end, value)| Need {
418                    entity,
419                    activity,
420                    start,
421                    end,
422                    value,
423                })
424        })
425    }
426
427    /// The ticks worth evaluating for any requirement, `None` without requirements.
428    fn coverage(&self, needs: &[Need]) -> Option<(Tick, Tick)> {
429        let settled = self.settled();
430        let from = needs
431            .iter()
432            .map(|need| self.starts(need.entity).earliest() + need.start);
433        let to = needs.iter().map(|need| self.last_tick(need, settled));
434        Some((from.min()?, to.max()?))
435    }
436
437    /// The ticks in `[from, to]` at which a mismatch verdict can start to hold, sorted.
438    ///
439    /// Every quantity the predicates compare is a constant (a window end plus an offset) or the
440    /// tick plus a constant (a difference of two offsets of one activity), so a comparison can
441    /// only flip where the tick equals such a constant minus such a difference. Taking these
442    /// points (and two ticks either side, for strict comparisons and the `+ 1` of half-open
443    /// ends) plus each requirement's first covered tick finds the start of every interval on
444    /// which a predicate holds, without walking long windows tick by tick.
445    fn candidate_ticks(&self, needs: &[Need], from: Tick, to: Tick) -> Result<Vec<Tick>, Error> {
446        let mut constants: Vec<i128> = Vec::new();
447        let mut shifts: Vec<i128> = Vec::new();
448        for (index, entity) in self.entities.iter().enumerate() {
449            let mut offsets: Vec<i128> = Vec::new();
450            offsets.push(0);
451            offsets.extend(entity.sets.iter().map(|&(offset, _, _)| i128::from(offset)));
452            for need in needs.iter().filter(|need| need.entity == index) {
453                offsets.extend([i128::from(need.start), i128::from(need.end)]);
454            }
455
456            offsets.sort_unstable();
457            offsets.dedup();
458            let (lo, hi) = (
459                i128::from(entity.window.earliest()),
460                i128::from(entity.window.latest()),
461            );
462            constants.extend(
463                offsets
464                    .iter()
465                    .flat_map(|&offset| [lo + offset, hi + offset]),
466            );
467            for &p in &offsets {
468                shifts.extend(offsets.iter().map(|&q| p - q));
469            }
470        }
471
472        constants.sort_unstable();
473        constants.dedup();
474        shifts.sort_unstable();
475        shifts.dedup();
476        let (from_wide, to_wide) = (i128::from(from), i128::from(to));
477        let mut ticks: Vec<Tick> = Vec::new();
478        let mut push = |tick: i128| -> Result<(), Error> {
479            if from_wide <= tick && tick <= to_wide {
480                ticks.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
481                ticks.push(Tick::try_from(tick).map_err(|_| Error::Overflow)?);
482            }
483
484            Ok(())
485        };
486        for need in needs {
487            push(i128::from(self.starts(need.entity).earliest()) + i128::from(need.start))?;
488        }
489
490        for &constant in &constants {
491            for &shift in &shifts {
492                for nudge in -2..=2 {
493                    push(constant - shift + nudge)?;
494                }
495            }
496        }
497
498        ticks.sort_unstable();
499        ticks.dedup();
500        Ok(ticks)
501    }
502
503    /// The latest tick any set can take, `None` without sets. After it every activity's
504    /// options are constant.
505    fn settled(&self) -> Option<Tick> {
506        self.set_ranges().map(|set| set.hi).max()
507    }
508
509    /// The last tick worth evaluating for `need`.
510    ///
511    /// Past both `settled` (the latest set tick) and the tick where every start of the
512    /// requirer covers the requirement, the other activities' options are constant, the
513    /// requirer's latest own set is fixed and its earliest covering start only grows. A
514    /// possible mismatch can then only disappear and a certain one stays as it is, so one tick
515    /// past both decides the rest of the (possibly unbounded) requirement.
516    fn last_tick(&self, need: &Need, settled: Option<Tick>) -> Tick {
517        let window = self.starts(need.entity);
518        let covered_end = i128::from(window.latest()) + i128::from(need.end) - 1;
519        let fully_covered = i128::from(window.latest()) + i128::from(need.start);
520        let settled = settled.map_or(i128::MIN, i128::from);
521        let last = covered_end.min(settled.max(fully_covered) + 1);
522        // The requirement end was validated to fit a tick at the latest start.
523        Tick::try_from(last).unwrap_or(Tick::MAX)
524    }
525
526    /// The start window of entity `index`.
527    fn starts(&self, index: usize) -> Window {
528        self.entities[index].window
529    }
530
531    /// Whether some start of the requirer makes the requirement cover `t`.
532    fn may_cover(&self, need: &Need, t: Tick) -> bool {
533        self.covering_starts(need, t).is_some()
534    }
535
536    /// The starts of the requirer for which the requirement covers `t`.
537    fn covering_starts(&self, need: &Need, t: Tick) -> Option<(i128, i128)> {
538        let window = self.starts(need.entity);
539        let t = i128::from(t);
540        let first = i128::from(window.earliest()).max(t - i128::from(need.end) + 1);
541        let last = i128::from(window.latest()).min(t - i128::from(need.start));
542        (first <= last).then_some((first, last))
543    }
544
545    /// The options of every entity at tick `t`.
546    fn options_at(&self, t: Tick) -> Result<Vec<Options<'_>>, Error> {
547        let mut all = Vec::new();
548        all.try_reserve_exact(self.entities.len())
549            .map_err(|_| Error::OutOfMemory)?;
550        for entity in &self.entities {
551            all.push(entity.options_at(t)?);
552        }
553
554        Ok(all)
555    }
556
557    /// Whether some schedule breaks `need` at `t`.
558    fn possibly_broken(
559        &self,
560        need: &Need,
561        t: Tick,
562        options: &[Options<'_>],
563    ) -> Result<bool, Error> {
564        let Some(starts) = self.covering_starts(need, t) else {
565            return Ok(false);
566        };
567
568        let others = |x: i128, skip: Option<usize>| {
569            options.iter().enumerate().all(|(index, other)| {
570                index == need.entity || Some(index) == skip || other.can_be_at_most(x)
571            })
572        };
573        for piece in self.entities[need.entity].pieces(t, starts)? {
574            let own_tick = piece
575                .own
576                .map(|(offset, _)| piece.first + i128::from(offset));
577            if let Some((offset, sets)) = piece.own {
578                let latest = piece.last + i128::from(offset);
579                let own = Opt {
580                    lo: latest,
581                    hi: latest,
582                    sets,
583                };
584                if own.differs_from(need.value) && others(latest, None) {
585                    return Ok(true);
586                }
587            }
588
589            for (index, other) in options.iter().enumerate() {
590                if index == need.entity {
591                    continue;
592                }
593
594                for option in other.options.iter().filter(|o| o.differs_from(need.value)) {
595                    let own_fits = own_tick.is_none_or(|own| own <= option.hi);
596                    if own_fits && others(option.hi, Some(index)) {
597                        return Ok(true);
598                    }
599                }
600            }
601
602            let all_none = options
603                .iter()
604                .enumerate()
605                .all(|(index, other)| index == need.entity || other.none);
606            if piece.own.is_none() && all_none && self.timeline.initial() != need.value {
607                return Ok(true);
608            }
609        }
610
611        Ok(false)
612    }
613
614    /// Whether every schedule breaks `need` at `t`.
615    fn certainly_broken(
616        &self,
617        need: &Need,
618        t: Tick,
619        options: &[Options<'_>],
620    ) -> Result<bool, Error> {
621        let window = self.starts(need.entity);
622        let starts = (i128::from(window.earliest()), i128::from(window.latest()));
623        if self.covering_starts(need, t) != Some(starts) {
624            return Ok(false);
625        }
626
627        let value = need.value;
628        let others = |x: i128, skip: Option<usize>| {
629            options.iter().enumerate().all(|(index, other)| {
630                index == need.entity || Some(index) == skip || other.can_yield_to(x, value)
631            })
632        };
633        for piece in self.entities[need.entity].pieces(t, starts)? {
634            if let Some((offset, sets)) = piece.own {
635                let latest = piece.last + i128::from(offset);
636                let own = Opt {
637                    lo: latest,
638                    hi: latest,
639                    sets,
640                };
641                if own.is_only(value) && others(latest, None) {
642                    return Ok(false);
643                }
644            }
645
646            for (index, other) in options.iter().enumerate() {
647                if index == need.entity {
648                    continue;
649                }
650
651                for option in other.options.iter().filter(|o| o.is_only(value)) {
652                    if piece_yields(&piece, option.hi, value) && others(option.hi, Some(index)) {
653                        return Ok(false);
654                    }
655                }
656            }
657
658            let all_none = options
659                .iter()
660                .enumerate()
661                .all(|(index, other)| index == need.entity || other.none);
662            if piece.own.is_none() && all_none && self.timeline.initial() == value {
663                return Ok(false);
664            }
665        }
666
667        Ok(true)
668    }
669}
670
671/// Whether the requirer's own latest set in `piece` can stay before `x`, or tie at `x` with
672/// sets of `value` only.
673fn piece_yields(piece: &Piece<'_>, x: i128, value: StateValue) -> bool {
674    let Some((offset, sets)) = piece.own else {
675        return true;
676    };
677
678    let offset = i128::from(offset);
679    let before = piece.first + offset < x;
680    let tie = (piece.first..=piece.last).contains(&(x - offset))
681        && sets.iter().all(|&(_, other, _)| other == value);
682    before || tie
683}
684
685/// A set with the ticks it can take.
686#[derive(Debug, Clone, Copy)]
687struct SetRange {
688    /// The entity it belongs to.
689    entity: usize,
690    /// Its tick relative to the entity's start.
691    offset: Tick,
692    /// The value it sets.
693    value: StateValue,
694    /// The activity that sets it.
695    activity: ActivityId,
696    /// Its earliest tick.
697    lo: Tick,
698    /// Its latest tick.
699    hi: Tick,
700}
701
702impl SetRange {
703    /// The earliest tick both sets can take at once, if their ranges meet.
704    fn meet(&self, other: &Self) -> Option<Tick> {
705        let lo = self.lo.max(other.lo);
706        (lo <= self.hi.min(other.hi)).then_some(lo)
707    }
708}
709
710impl Entity {
711    /// The options at tick `t`.
712    fn options_at(&self, t: Tick) -> Result<Options<'_>, Error> {
713        let t = i128::from(t);
714        let (lo, hi) = (
715            i128::from(self.window.earliest()),
716            i128::from(self.window.latest()),
717        );
718        let mut options = Vec::new();
719        let groups = self.groups();
720        let none = groups
721            .first()
722            .is_none_or(|&(offset, _)| hi + i128::from(offset) > t);
723        for (index, &(offset, sets)) in groups.iter().enumerate() {
724            let offset = i128::from(offset);
725            let after = groups
726                .get(index + 1)
727                .map_or(lo, |&(next, _)| t - i128::from(next) + 1);
728            let first = lo.max(after);
729            let last = hi.min(t - offset);
730            if first <= last {
731                options.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
732                options.push(Opt {
733                    lo: first + offset,
734                    hi: last + offset,
735                    sets,
736                });
737            }
738        }
739
740        Ok(Options { none, options })
741    }
742
743    /// The sets grouped by offset, ascending.
744    fn groups(&self) -> Vec<(Tick, &[SetEntry])> {
745        let mut groups = Vec::new();
746        let mut rest = self.sets.as_slice();
747        while let Some(&(offset, _, _)) = rest.first() {
748            let count = rest.iter().take_while(|set| set.0 == offset).count();
749            let (now, later) = rest.split_at(count);
750            groups.push((offset, now));
751            rest = later;
752        }
753
754        groups
755    }
756
757    /// The pieces of the starts `[first, last]` with the same latest own set at `t`.
758    fn pieces(&self, t: Tick, (first, last): (i128, i128)) -> Result<Vec<Piece<'_>>, Error> {
759        let t = i128::from(t);
760        let groups = self.groups();
761        let mut pieces = Vec::new();
762        pieces
763            .try_reserve(groups.len() + 1)
764            .map_err(|_| Error::OutOfMemory)?;
765        // No own set yet: t - s < first offset, that is s > t - first offset.
766        let none_from = groups
767            .first()
768            .map_or(first, |&(offset, _)| first.max(t - i128::from(offset) + 1));
769        if none_from <= last {
770            pieces.push(Piece {
771                first: none_from,
772                last,
773                own: None,
774            });
775        }
776
777        for (index, &(offset, sets)) in groups.iter().enumerate() {
778            let from = groups
779                .get(index + 1)
780                .map_or(first, |&(next, _)| first.max(t - i128::from(next) + 1));
781            let to = last.min(t - i128::from(offset));
782            if from <= to {
783                pieces.push(Piece {
784                    first: from,
785                    last: to,
786                    own: Some((offset, sets)),
787                });
788            }
789        }
790
791        Ok(pieces)
792    }
793}
794
795/// The entity of the given impacts with start window `window`.
796fn entity(
797    window: Window,
798    impacts: impl Iterator<Item = (ActivityId, StateImpact)>,
799) -> Result<Entity, Error> {
800    let mut entity = Entity {
801        window,
802        sets: Vec::new(),
803        requires: Vec::new(),
804    };
805    for (activity, impact) in impacts {
806        match impact {
807            StateImpact::Set { at, value } => {
808                entity.sets.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
809                entity.sets.push((at, value, activity));
810            }
811            StateImpact::Require { start, end, value } => {
812                entity
813                    .requires
814                    .try_reserve(1)
815                    .map_err(|_| Error::OutOfMemory)?;
816                entity.requires.push((activity, start, end, value));
817            }
818        }
819    }
820
821    entity.sets.sort_unstable();
822    Ok(entity)
823}
824
825/// The earlier of a conflict and a mismatch; a conflict wins at the same tick.
826fn earliest(
827    conflict: Option<StateEnvelopeViolation>,
828    mismatch: Option<StateEnvelopeViolation>,
829) -> Option<StateEnvelopeViolation> {
830    match (conflict, mismatch) {
831        (Some(conflict), Some(mismatch)) if mismatch.at() < conflict.at() => Some(mismatch),
832        (Some(conflict), _) => Some(conflict),
833        (None, mismatch) => mismatch,
834    }
835}