pub struct Timeline<S: Storage = Heap> { /* private fields */ }Expand description
The level of one resource over time, built from activity impacts.
The storage S is storage::Heap by default; with
Fixed<N> the timeline holds at most N impacts and never
allocates (see storage). Heap timelines are created with
depletable and claimable, timelines with any
storage with depletable_in and claimable_in.
The level starts at an initial value at the start tick and changes only through impacts. It is piecewise linear: steps and claims make it jump, rates give it a slope. Checks cover every tick from the start onward; after the last impact ends the level is constant.
The timeline keeps its impacts and, alongside them, a sorted list of change points that is
updated on every add and remove. A check sweeps the change
points once without sorting or allocating.
§Examples
use resource_timeline::{ActivityId, Bound, Bounds, Impact, Timeline};
// Battery at 50 units, reserve 10. A drive drains 3 units per tick from tick 0 to tick 20.
let mut battery = Timeline::depletable(0, 50, Bounds::new(10, 100)?, 8)?;
battery.add(ActivityId(1), Impact::Rate { start: 0, end: 20, per_tick: -3 })?;
let violation = battery.first_violation()?.expect("the reserve is broken");
assert_eq!(violation.at, 14); // 50 - 3 * 14 = 8 < 10
assert_eq!(violation.level, 8);
assert_eq!(violation.bound, Bound::BelowMin(10));
// Cancelling the drive restores the battery.
assert_eq!(battery.remove(ActivityId(1)), 1);
assert_eq!(battery.first_violation()?, None);Implementations§
Source§impl<S: Storage> Timeline<S>
impl<S: Storage> Timeline<S>
Sourcepub fn encoded_len(&self) -> usize
pub fn encoded_len(&self) -> usize
The number of bytes encode writes.
Sourcepub fn encode(&self, out: &mut [u8]) -> Result<usize, Error>
pub fn encode(&self, out: &mut [u8]) -> Result<usize, Error>
Writes the timeline (kind, start, initial level, bounds, budget, impacts in insertion
order, targets) into out and returns the number of bytes written; see the
codec module for the format and an example.
§Errors
Error::BufferTooSmall if out is shorter than encoded_len;
nothing is written then. Error::Overflow if a count exceeds u32.
Sourcepub fn decode_in(bytes: &[u8]) -> Result<Self, Error>
pub fn decode_in(bytes: &[u8]) -> Result<Self, Error>
Reads a timeline written by encode, into storage S.
§Errors
Error::Malformed,Error::UnsupportedVersionorError::ChecksumMismatchas forLevelProfile::decode_in.- The errors of
Timeline::claimable_in,Timeline::addandTimeline::add_targetfor the decoded content, including capacity errors ifSis smaller than the encoded timeline.
Source§impl<S: Storage> Timeline<S>
impl<S: Storage> Timeline<S>
Sourcepub fn breakpoints(&self) -> Breakpoints<'_> ⓘ
pub fn breakpoints(&self) -> Breakpoints<'_> ⓘ
The ticks at which the level line changes, in time order.
The first breakpoint is at the start tick. A tick where impacts net to zero is no
breakpoint. Costs O(n) in total and never allocates. Targets are not part of the line.
§Examples
use resource_timeline::{ActivityId, Bounds, Breakpoint, Impact, Timeline};
let mut battery = Timeline::depletable(0, 50, Bounds::new(0, 100)?, 8)?;
battery.add(ActivityId(1), Impact::Rate { start: 10, end: 20, per_tick: -2 })?;
battery.add(ActivityId(2), Impact::Step { at: 30, delta: 5 })?;
let points: Vec<Breakpoint> = battery.breakpoints().collect::<Result<_, _>>()?;
assert_eq!(points, [
Breakpoint { at: 0, level: 50, slope: 0 },
Breakpoint { at: 10, level: 50, slope: -2 },
Breakpoint { at: 20, level: 30, slope: 0 },
Breakpoint { at: 30, level: 35, slope: 0 },
]);Sourcepub fn samples(
&self,
from: Tick,
step: Tick,
count: usize,
) -> Result<Samples<'_>, Error>
pub fn samples( &self, from: Tick, step: Tick, count: usize, ) -> Result<Samples<'_>, Error>
The level at count ticks from, from + step, from + 2 step, and so on.
Costs O(n + count) and never allocates. The samples stop early if a tick would
overflow; an item is an error if its level does not fit a Level.
§Errors
Error::BeforeStartiffromprecedes the timeline start.Error::InvalidStepifstepis not positive.
§Examples
use resource_timeline::{ActivityId, Bounds, Impact, Timeline};
let mut battery = Timeline::depletable(0, 50, Bounds::new(0, 100)?, 8)?;
battery.add(ActivityId(1), Impact::Rate { start: 10, end: 20, per_tick: -2 })?;
let telemetry: Vec<(i64, i64)> = battery.samples(0, 5, 6)?.collect::<Result<_, _>>()?;
assert_eq!(telemetry, [(0, 50), (5, 50), (10, 50), (15, 40), (20, 30), (25, 30)]);Sourcepub fn export(&self) -> Result<LevelProfile<S>, Error>
pub fn export(&self) -> Result<LevelProfile<S>, Error>
A self-contained copy of the level line, with the timeline’s storage.
§Errors
Error::Overflowif a level or slope does not fit aLevel.Error::OutOfMemoryif the breakpoint list cannot be allocated (heap storage). Fixed storage always has room.
§Examples
use resource_timeline::storage::Fixed;
use resource_timeline::{ActivityId, Bounds, Impact, Timeline};
let mut battery = Timeline::<Fixed<4>>::depletable_in(0, 50, Bounds::new(0, 100)?, 4)?;
battery.add(ActivityId(1), Impact::Rate { start: 10, end: 20, per_tick: -2 })?;
let profile = battery.export()?;
assert_eq!(profile.len(), 3);
assert_eq!(profile.level_at(15)?, battery.level_at(15)?);Source§impl Timeline
impl Timeline
Sourcepub const fn depletable(
start: Tick,
initial: Level,
bounds: Bounds,
budget: usize,
) -> Result<Self, Error>
pub const fn depletable( start: Tick, initial: Level, bounds: Bounds, budget: usize, ) -> Result<Self, Error>
Creates a heap timeline for a depletable resource such as battery energy or storage.
initial is the level at start. budget caps the number of impacts.
§Errors
Never fails today; returns Result so later validation does not break callers.
Sourcepub const fn claimable(
start: Tick,
capacity: Level,
budget: usize,
) -> Result<Self, Error>
pub const fn claimable( start: Tick, capacity: Level, budget: usize, ) -> Result<Self, Error>
Creates a heap timeline for a claimable resource with capacity units, all available
at start.
The bounds are [0, capacity], so overlapping claims may never hold more than
capacity units. budget caps the number of impacts.
§Errors
Returns Error::InvalidBounds if capacity is negative.
Source§impl<S: Storage> Timeline<S>
impl<S: Storage> Timeline<S>
Sourcepub const fn depletable_in(
start: Tick,
initial: Level,
bounds: Bounds,
budget: usize,
) -> Result<Self, Error>
pub const fn depletable_in( start: Tick, initial: Level, bounds: Bounds, budget: usize, ) -> Result<Self, Error>
Creates a timeline with storage S for a depletable resource such as battery energy.
As Timeline::depletable, for any Storage. With Fixed<N>
a budget above N is allowed, but adds beyond N fail with
Error::CapacityExceeded.
§Errors
Never fails today; returns Result so later validation does not break callers.
§Examples
use resource_timeline::storage::Fixed;
use resource_timeline::{Bounds, Timeline};
let battery = Timeline::<Fixed<32>>::depletable_in(0, 100, Bounds::new(20, 120)?, 32)?;
assert_eq!(battery.level_at(1_000)?, 100);Sourcepub const fn claimable_in(
start: Tick,
capacity: Level,
budget: usize,
) -> Result<Self, Error>
pub const fn claimable_in( start: Tick, capacity: Level, budget: usize, ) -> Result<Self, Error>
Creates a timeline with storage S for a claimable resource with capacity units.
As Timeline::claimable, for any Storage.
§Errors
Returns Error::InvalidBounds if capacity is negative.
Sourcepub const fn initial(&self) -> Level
pub const fn initial(&self) -> Level
The level at the start tick, before impacts at the start tick apply.
Sourcepub fn impacts(&self) -> &[(ActivityId, Impact)]
pub fn impacts(&self) -> &[(ActivityId, Impact)]
The impacts added so far, in insertion order.
Sourcepub fn add(&mut self, activity: ActivityId, impact: Impact) -> Result<(), Error>
pub fn add(&mut self, activity: ActivityId, impact: Impact) -> Result<(), Error>
Adds an impact of activity to the timeline.
The impact is validated but not checked against the bounds; call
first_violation for that.
§Errors
Error::KindMismatchif a step or rate is added to a claimable timeline.Error::BeforeStartif the impact takes effect before the timeline start.Error::EmptyIntervalif a claim or rate hasend <= start.Error::NonPositiveAmountif a claim amount is zero or negative.Error::BudgetExhaustedif the timeline already holdsbudgetimpacts.Error::OutOfMemoryif the impact list cannot grow (heap storage).Error::CapacityExceededif the impact list or the change points are full (fixed storage).
The timeline is unchanged on error.
Sourcepub fn remove(&mut self, activity: ActivityId) -> usize
pub fn remove(&mut self, activity: ActivityId) -> usize
Removes every impact of activity and returns how many there were.
Never allocates. Costs O(n) for the impact list plus O(n) per removed impact for
the change points. Removing an activity without impacts is a no-op that returns 0.
Sourcepub fn add_target(&mut self, target: Target) -> Result<(), Error>
pub fn add_target(&mut self, target: Target) -> Result<(), Error>
Requires the level at target.at to be at least target.min.
Targets do not count against the impact budget. Several targets may share a tick; the
strictest one is reported first. See Target for an example.
§Errors
Error::BeforeStartif the target precedes the timeline start.Error::OutOfMemoryif the target list cannot grow (heap storage).Error::CapacityExceedednamingContainer::Targetsif it is full (fixed storage).
Sourcepub fn targets(&self) -> &[Target]
pub fn targets(&self) -> &[Target]
The end-state targets, sorted by tick and, within a tick, strictest first.
Sourcepub fn remove_targets_at(&mut self, at: Tick) -> usize
pub fn remove_targets_at(&mut self, at: Tick) -> usize
Removes every target at tick at and returns how many there were. Never allocates.
Sourcepub fn level_at(&self, t: Tick) -> Result<Level, Error>
pub fn level_at(&self, t: Tick) -> Result<Level, Error>
The level at tick t, with all impacts at t applied.
Costs O(n) for n impacts.
§Errors
Error::BeforeStartiftprecedes the timeline start, where no level is defined.Error::Overflowif the level does not fit aLevel.
Sourcepub fn has_rates(&self) -> bool
pub fn has_rates(&self) -> bool
Whether any impact on this timeline is a Impact::Rate with a non-zero rate.
Sourcepub fn first_violation(&self) -> Result<Option<Violation<S>>, Error>
pub fn first_violation(&self) -> Result<Option<Violation<S>>, Error>
Finds the earliest tick at which the level is outside the bounds or misses a
Target.
At the same tick, a broken bound is reported before a missed target.
All impacts at a tick are netted before the level is compared, so a claim ending at t
and another starting at t never overlap. Along a rate the exact crossing tick is
found by integer division, not by stepping tick by tick. Runs in O(n) time over the
change points; only the explanation of a violation allocates O(n) memory. The result
does not depend on insertion order.
Returns Ok(None) if the level stays within the bounds forever.
§Errors
Error::Overflowif a running sum exceedsi128, or if the level at the first violation does not fit aLevel. A violation exists in the second case, but it cannot be reported exactly.Error::OutOfMemoryif the working memory cannot be allocated (heap storage). Fixed storage has room for its explanation by construction.