resource_timeline/error.rs
1//! Errors of timeline construction, impact insertion and checks.
2
3use core::fmt;
4
5use crate::{Level, Tick};
6
7/// Why a timeline could not be built, an impact was rejected, or a check could not finish.
8///
9/// None of these is a resource violation. A violation is a successful check result, see
10/// [`Violation`](crate::Violation).
11///
12/// The enum is `#[non_exhaustive]`: new failure modes (for example of future checks) are added
13/// without a breaking release, so a `match` needs a wildcard arm. Callers that only need the
14/// distinction "retry with more room" versus "malformed input" can use
15/// [`is_capacity`](Self::is_capacity).
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17#[non_exhaustive]
18pub enum Error {
19 /// The lower bound is greater than the upper bound, or a claimable capacity is negative.
20 InvalidBounds {
21 /// The requested lower bound.
22 min: Level,
23 /// The requested upper bound.
24 max: Level,
25 },
26 /// The timeline already holds as many impacts as its budget allows.
27 BudgetExhausted {
28 /// The impact budget the timeline was created with.
29 limit: usize,
30 },
31 /// An impact starts before the timeline start.
32 BeforeStart {
33 /// The first tick of the rejected impact.
34 at: Tick,
35 /// The start tick of the timeline.
36 start: Tick,
37 },
38 /// A claim or rate interval `[start, end)` is empty or inverted.
39 EmptyInterval {
40 /// The requested first tick.
41 start: Tick,
42 /// The requested end tick.
43 end: Tick,
44 },
45 /// A claim amount is zero or negative.
46 NonPositiveAmount {
47 /// The rejected amount.
48 amount: Level,
49 },
50 /// A step or rate impact was added to a claimable timeline, which accepts claims only.
51 KindMismatch,
52 /// An intermediate sum, or the level at the first violation, does not fit the number range.
53 Overflow,
54 /// Memory for the impact list or the check could not be allocated.
55 OutOfMemory,
56 /// A fixed-capacity container is full.
57 ///
58 /// Only fixed-capacity storage ([`Fixed`](crate::storage::Fixed),
59 /// [`FixedPlan`](crate::storage::FixedPlan)) reports this; heap storage reports
60 /// [`OutOfMemory`](Self::OutOfMemory) instead. The operation that failed left its target
61 /// unchanged.
62 CapacityExceeded {
63 /// Which container ran out of room.
64 container: Container,
65 /// The fixed capacity of that container, in elements.
66 capacity: usize,
67 },
68 /// A start window has `earliest > latest`.
69 InvalidWindow {
70 /// The requested earliest start.
71 earliest: Tick,
72 /// The requested latest start.
73 latest: Tick,
74 },
75 /// An output buffer is too short for an encoding.
76 BufferTooSmall {
77 /// The number of bytes the encoding needs.
78 needed: usize,
79 },
80 /// Encoded bytes have the wrong magic, length or content.
81 Malformed,
82 /// Encoded bytes do not match their checksum.
83 ChecksumMismatch,
84 /// Encoded bytes use a format version this build does not read.
85 UnsupportedVersion {
86 /// The version found.
87 version: u8,
88 },
89 /// A sampling step is zero or negative.
90 InvalidStep {
91 /// The rejected step.
92 step: Tick,
93 },
94 /// A demand names a timeline that is not part of the plan.
95 UnknownResource,
96 /// A precedence names an activity that is not part of the envelope.
97 UnknownActivity {
98 /// The unknown activity.
99 activity: crate::ActivityId,
100 },
101 /// The start windows and precedences of an envelope admit no schedule at all.
102 InconsistentPrecedences,
103 /// A duration range of an activity starts below zero.
104 NegativeDuration {
105 /// The requested shortest duration.
106 shortest: Tick,
107 },
108 /// A search ran out of its caller-chosen number of candidate checks before it found an
109 /// answer.
110 SearchExhausted {
111 /// The number of candidate checks the search was allowed.
112 checks: usize,
113 },
114}
115
116/// The containers a timeline, plan or check keeps, named in [`Error::CapacityExceeded`].
117///
118/// With [`Fixed<N>`](crate::storage::Fixed) storage, the per-timeline containers hold `N`
119/// elements, except [`ChangePoints`](Self::ChangePoints), which holds `2 N` (every impact
120/// changes the level at most at two ticks). [`FixedPlan`](crate::storage::FixedPlan) adds its
121/// own capacities for [`Timelines`](Self::Timelines) and [`States`](Self::States).
122#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
123#[non_exhaustive]
124pub enum Container {
125 /// The impacts of a numeric or state timeline.
126 Impacts,
127 /// The sorted change points of a numeric timeline.
128 ChangePoints,
129 /// The end-state targets of a numeric timeline.
130 Targets,
131 /// The sorted sets of a state timeline.
132 Sets,
133 /// The requirements of a state timeline.
134 Requirements,
135 /// The numeric timelines of a plan.
136 Timelines,
137 /// The state timelines of a plan.
138 States,
139 /// The contributor or setter list of a violation explanation.
140 Contributors,
141 /// Working memory of a check or search, sized like the impacts of one timeline.
142 Scratch,
143}
144
145impl Error {
146 /// Whether the error means "no room": [`OutOfMemory`](Self::OutOfMemory),
147 /// [`CapacityExceeded`](Self::CapacityExceeded) or [`BudgetExhausted`](Self::BudgetExhausted).
148 ///
149 /// These depend on the chosen limits, not on the input being malformed, so a caller may
150 /// retry with larger limits or shed load.
151 #[must_use]
152 pub const fn is_capacity(&self) -> bool {
153 matches!(
154 self,
155 Self::OutOfMemory | Self::CapacityExceeded { .. } | Self::BudgetExhausted { .. }
156 )
157 }
158}
159
160impl fmt::Display for Container {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 f.write_str(match self {
163 Self::Impacts => "impact list",
164 Self::ChangePoints => "change-point list",
165 Self::Targets => "target list",
166 Self::Sets => "set list",
167 Self::Requirements => "requirement list",
168 Self::Timelines => "timeline list",
169 Self::States => "state timeline list",
170 Self::Contributors => "contributor list",
171 Self::Scratch => "scratch buffer",
172 })
173 }
174}
175
176impl fmt::Display for Error {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 match *self {
179 Self::InvalidBounds { min, max } => write!(f, "invalid bounds [{min}, {max}]"),
180 Self::BudgetExhausted { limit } => write!(f, "impact budget of {limit} exhausted"),
181 Self::BeforeStart { at, start } => {
182 write!(f, "impact at tick {at} precedes timeline start {start}")
183 }
184 Self::EmptyInterval { start, end } => write!(f, "empty interval [{start}, {end})"),
185 Self::NonPositiveAmount { amount } => {
186 write!(f, "claim amount {amount} is not positive")
187 }
188 Self::KindMismatch => f.write_str("claimable timelines accept claims only"),
189 Self::Overflow => f.write_str("arithmetic overflow"),
190 Self::OutOfMemory => f.write_str("allocation failed"),
191 Self::CapacityExceeded {
192 container,
193 capacity,
194 } => write!(f, "{container} is full at {capacity} elements"),
195 Self::InvalidWindow { earliest, latest } => {
196 write!(f, "invalid start window [{earliest}, {latest}]")
197 }
198 Self::BufferTooSmall { needed } => write!(f, "buffer too small, {needed} bytes needed"),
199 Self::Malformed => f.write_str("malformed encoding"),
200 Self::ChecksumMismatch => f.write_str("checksum mismatch"),
201 Self::UnsupportedVersion { version } => {
202 write!(f, "unsupported encoding version {version}")
203 }
204 Self::InvalidStep { step } => write!(f, "sampling step {step} is not positive"),
205 Self::UnknownResource => f.write_str("demand names an unknown timeline"),
206 Self::UnknownActivity { activity } => {
207 write!(f, "precedence names unknown activity {}", activity.0)
208 }
209 Self::InconsistentPrecedences => f.write_str("precedences admit no schedule"),
210 Self::NegativeDuration { shortest } => {
211 write!(f, "shortest duration {shortest} is negative")
212 }
213 Self::SearchExhausted { checks } => {
214 write!(f, "search exhausted its budget of {checks} checks")
215 }
216 }
217 }
218}
219
220impl core::error::Error for Error {}