Skip to main content

Timeline

Struct Timeline 

Source
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>

Source

pub fn encoded_len(&self) -> usize

The number of bytes encode writes.

Source

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.

Source

pub fn decode_in(bytes: &[u8]) -> Result<Self, Error>

Reads a timeline written by encode, into storage S.

§Errors
Source§

impl Timeline

Source

pub fn decode(bytes: &[u8]) -> Result<Self, Error>

decode_in into heap storage.

§Errors

As for decode_in.

Source§

impl<S: Storage> Timeline<S>

Source

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 },
]);
Source

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
§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)]);
Source

pub fn export(&self) -> Result<LevelProfile<S>, Error>

A self-contained copy of the level line, with the timeline’s storage.

§Errors
§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

Source

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.

Source

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>

Source

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);
Source

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.

Source

pub const fn kind(&self) -> Kind

Which impacts the timeline accepts.

Source

pub const fn start(&self) -> Tick

The first tick of the timeline.

Source

pub const fn initial(&self) -> Level

The level at the start tick, before impacts at the start tick apply.

Source

pub const fn bounds(&self) -> Bounds

The range the level must stay in.

Source

pub const fn budget(&self) -> usize

The maximum number of impacts the timeline accepts.

Source

pub fn impacts(&self) -> &[(ActivityId, Impact)]

The impacts added so far, in insertion order.

Source

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

The timeline is unchanged on error.

Source

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.

Source

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
Source

pub fn targets(&self) -> &[Target]

The end-state targets, sorted by tick and, within a tick, strictest first.

Source

pub fn remove_targets_at(&mut self, at: Tick) -> usize

Removes every target at tick at and returns how many there were. Never allocates.

Source

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
Source

pub fn has_rates(&self) -> bool

Whether any impact on this timeline is a Impact::Rate with a non-zero rate.

Source

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::Overflow if a running sum exceeds i128, or if the level at the first violation does not fit a Level. A violation exists in the second case, but it cannot be reported exactly.
  • Error::OutOfMemory if the working memory cannot be allocated (heap storage). Fixed storage has room for its explanation by construction.

Trait Implementations§

Source§

impl<S: Clone + Storage> Clone for Timeline<S>
where S::List<(ActivityId, Impact)>: Clone, S::List<Target>: Clone,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<S: Debug + Storage> Debug for Timeline<S>
where S::List<(ActivityId, Impact)>: Debug, S::List<Target>: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de, S: Storage> Deserialize<'de> for Timeline<S>

Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<S: Eq + Storage> Eq for Timeline<S>
where S::List<(ActivityId, Impact)>: Eq, S::List<Target>: Eq,

Source§

impl<S: Hash + Storage> Hash for Timeline<S>
where S::List<(ActivityId, Impact)>: Hash, S::List<Target>: Hash,

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<S: PartialEq + Storage> PartialEq for Timeline<S>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<S: Storage> Serialize for Timeline<S>

Source§

fn serialize<Z: Serializer>(&self, serializer: Z) -> Result<Z::Ok, Z::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl<S: Storage> Slot for Timeline<S>

Source§

const EMPTY: Self

The filler of unused slots. Never observable through a container.
Source§

impl<S: PartialEq + Storage> StructuralPartialEq for Timeline<S>

Auto Trait Implementations§

§

impl<S> Forget for Timeline<S>

§

impl<S> Freeze for Timeline<S>
where <S as Storage>::List<(ActivityId, Impact)>: Freeze, Profile<S>: Freeze, <S as Storage>::List<Target>: Freeze,

§

impl<S> Move for Timeline<S>

§

impl<S> RefUnwindSafe for Timeline<S>

§

impl<S> Send for Timeline<S>
where <S as Storage>::List<(ActivityId, Impact)>: Send, Profile<S>: Send, <S as Storage>::List<Target>: Send,

§

impl<S> Sync for Timeline<S>
where <S as Storage>::List<(ActivityId, Impact)>: Sync, Profile<S>: Sync, <S as Storage>::List<Target>: Sync,

§

impl<S> Unpin for Timeline<S>
where <S as Storage>::List<(ActivityId, Impact)>: Unpin, Profile<S>: Unpin, <S as Storage>::List<Target>: Unpin,

§

impl<S> UnsafeUnpin for Timeline<S>
where <S as Storage>::List<(ActivityId, Impact)>: UnsafeUnpin, Profile<S>: UnsafeUnpin, <S as Storage>::List<Target>: UnsafeUnpin,

§

impl<S> UnwindSafe for Timeline<S>
where <S as Storage>::List<(ActivityId, Impact)>: UnwindSafe, Profile<S>: UnwindSafe, <S as Storage>::List<Target>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.