StateHistory

Struct StateHistory 

Source
pub struct StateHistory<S: State> { /* private fields */ }
Expand description

Ordered history of state transitions.

History is immutable - the record method returns a new history with the transition added, following functional programming principles.

§Example

use mindset::core::{State, StateHistory, StateTransition};
use serde::{Deserialize, Serialize};
use chrono::Utc;

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
enum WorkState {
    Start,
    Middle,
    End,
}

impl State for WorkState {
    fn name(&self) -> &str {
        match self {
            Self::Start => "Start",
            Self::Middle => "Middle",
            Self::End => "End",
        }
    }
}

let history = StateHistory::new();

let transition1 = StateTransition {
    from: WorkState::Start,
    to: WorkState::Middle,
    timestamp: Utc::now(),
    attempt: 1,
};

let history = history.record(transition1);

let transition2 = StateTransition {
    from: WorkState::Middle,
    to: WorkState::End,
    timestamp: Utc::now(),
    attempt: 1,
};

let history = history.record(transition2);

let path = history.get_path();
assert_eq!(path.len(), 3); // Start -> Middle -> End

Implementations§

Source§

impl<S: State> StateHistory<S>

Source

pub fn new() -> Self

Create a new empty history.

§Example
use mindset::core::{State, StateHistory};
use serde::{Deserialize, Serialize};

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
enum Status { Active }

impl State for Status {
    fn name(&self) -> &str { "Active" }
}

let history: StateHistory<Status> = StateHistory::new();
assert_eq!(history.transitions().len(), 0);
Source

pub fn record(&self, transition: StateTransition<S>) -> Self

Record a transition, returning a new history.

This is a pure function - it does not mutate the existing history but returns a new one with the transition added.

§Example
use mindset::core::{State, StateHistory, StateTransition};
use serde::{Deserialize, Serialize};
use chrono::Utc;

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
enum Step { A, B }

impl State for Step {
    fn name(&self) -> &str {
        match self {
            Self::A => "A",
            Self::B => "B",
        }
    }
}

let history = StateHistory::new();
let transition = StateTransition {
    from: Step::A,
    to: Step::B,
    timestamp: Utc::now(),
    attempt: 1,
};

let new_history = history.record(transition);
assert_eq!(new_history.transitions().len(), 1);
assert_eq!(history.transitions().len(), 0); // Original unchanged
Source

pub fn get_path(&self) -> Vec<&S>

Get the path of states traversed.

Returns references to states in order: initial state, then the to state of each transition.

§Example
use mindset::core::{State, StateHistory, StateTransition};
use serde::{Deserialize, Serialize};
use chrono::Utc;

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
enum Phase { One, Two, Three }

impl State for Phase {
    fn name(&self) -> &str {
        match self {
            Self::One => "One",
            Self::Two => "Two",
            Self::Three => "Three",
        }
    }
}

let mut history = StateHistory::new();

history = history.record(StateTransition {
    from: Phase::One,
    to: Phase::Two,
    timestamp: Utc::now(),
    attempt: 1,
});

history = history.record(StateTransition {
    from: Phase::Two,
    to: Phase::Three,
    timestamp: Utc::now(),
    attempt: 1,
});

let path = history.get_path();
assert_eq!(path.len(), 3);
assert_eq!(path[0], &Phase::One);
assert_eq!(path[1], &Phase::Two);
assert_eq!(path[2], &Phase::Three);
Source

pub fn duration(&self) -> Option<Duration>

Calculate total duration from first to last transition.

Returns None if there are no transitions. Otherwise returns the duration between the first and last transition timestamps.

§Example
use mindset::core::{State, StateHistory, StateTransition};
use serde::{Deserialize, Serialize};
use chrono::Utc;

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
enum State1 { A, B }

impl State for State1 {
    fn name(&self) -> &str {
        match self {
            Self::A => "A",
            Self::B => "B",
        }
    }
}

let history = StateHistory::new();
assert!(history.duration().is_none());

let start = Utc::now();
let history = history.record(StateTransition {
    from: State1::A,
    to: State1::B,
    timestamp: start,
    attempt: 1,
});

assert!(history.duration().is_some());
Source

pub fn transitions(&self) -> &[StateTransition<S>]

Get all transitions.

Returns a slice of all recorded transitions in order.

§Example
use mindset::core::{State, StateHistory, StateTransition};
use serde::{Deserialize, Serialize};
use chrono::Utc;

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
enum MyState { X, Y }

impl State for MyState {
    fn name(&self) -> &str {
        match self {
            Self::X => "X",
            Self::Y => "Y",
        }
    }
}

let history = StateHistory::new();
let history = history.record(StateTransition {
    from: MyState::X,
    to: MyState::Y,
    timestamp: Utc::now(),
    attempt: 1,
});

assert_eq!(history.transitions().len(), 1);

Trait Implementations§

Source§

impl<S: Clone + State> Clone for StateHistory<S>

Source§

fn clone(&self) -> StateHistory<S>

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<S: Debug + State> Debug for StateHistory<S>

Source§

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

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

impl<S: State> Default for StateHistory<S>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, S: State> Deserialize<'de> for StateHistory<S>

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

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

impl<S: State> Serialize for StateHistory<S>

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<S> Freeze for StateHistory<S>

§

impl<S> RefUnwindSafe for StateHistory<S>
where S: RefUnwindSafe,

§

impl<S> Send for StateHistory<S>

§

impl<S> Sync for StateHistory<S>

§

impl<S> Unpin for StateHistory<S>
where S: Unpin,

§

impl<S> UnwindSafe for StateHistory<S>
where S: 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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

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