sovran_state

Struct Store

Source
pub struct Store { /* private fields */ }
Expand description

The Store struct holding multiple containers for different state types.

Implementations§

Source§

impl Store

Source

pub fn new() -> Self

Creates a new, empty store.

§Returns

A new instance of Store.

§Examples
use sovran_state::Store;

let store = Store::new();
Examples found in repository?
examples/sovran_example.rs (line 81)
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
fn main() {
    // Create store and provide initial state
    let store = Arc::new(Store::new());
    store.provide(BankState {
        balance: 1000.0,
        transaction_count: 0,
    }).expect("Failed to provide initial state");

    // Create our components
    let monitor = AccountMonitor::new(store.clone());
    let _logger = TransactionLogger::new(store.clone());

    println!("Initial balance: ${:.2}", monitor.check_balance());

    // Simulate some transactions
    println!("\nProcessing transactions...\n");

    // Deposit
    store.dispatch(DepositAction(500.0))
        .expect("Failed to process deposit");
    thread::sleep(Duration::from_millis(500));

    // Withdraw
    store.dispatch(WithdrawAction(200.0))
        .expect("Failed to process withdrawal");
    thread::sleep(Duration::from_millis(500));

    // Deposit again
    store.dispatch(DepositAction(750.0))
        .expect("Failed to process deposit");
    thread::sleep(Duration::from_millis(500));

    println!("\nFinal balance: ${:.2}", monitor.check_balance());
}
Source

pub fn provide<S: State>(&self, initial_state: S) -> Result<(), StoreError>

Provides an initial state of a certain type to the store.

§Arguments
  • initial_state - The initial state to be held in the store.
§Returns

A Result indicating success or failure.

§Examples
use sovran_state::{Store, State, StoreError};

#[derive(Clone, Debug)]
struct MyState {
    value: i32,
}

impl State for MyState {}

let store = Store::new();
match store.provide(MyState { value: 20 }) {
    Ok(_) => println!("State provided successfully"),
    Err(err) => println!("Failed to provide state: {:?}", err),
}
Examples found in repository?
examples/sovran_example.rs (lines 82-85)
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
fn main() {
    // Create store and provide initial state
    let store = Arc::new(Store::new());
    store.provide(BankState {
        balance: 1000.0,
        transaction_count: 0,
    }).expect("Failed to provide initial state");

    // Create our components
    let monitor = AccountMonitor::new(store.clone());
    let _logger = TransactionLogger::new(store.clone());

    println!("Initial balance: ${:.2}", monitor.check_balance());

    // Simulate some transactions
    println!("\nProcessing transactions...\n");

    // Deposit
    store.dispatch(DepositAction(500.0))
        .expect("Failed to process deposit");
    thread::sleep(Duration::from_millis(500));

    // Withdraw
    store.dispatch(WithdrawAction(200.0))
        .expect("Failed to process withdrawal");
    thread::sleep(Duration::from_millis(500));

    // Deposit again
    store.dispatch(DepositAction(750.0))
        .expect("Failed to process deposit");
    thread::sleep(Duration::from_millis(500));

    println!("\nFinal balance: ${:.2}", monitor.check_balance());
}
Source

pub fn get_state<S: State>(&self) -> Result<S, StoreError>

Retrieves the current state of a given type.

§Returns

A Result containing the state on success, or a StoreError on failure.

§Examples
use sovran_state::{Store, State, StoreError};

#[derive(Clone, Debug)]
struct MyState {
    value: i32,
}

impl State for MyState {}

let store = Store::new();
store.provide(MyState { value: 20 }).unwrap();
match store.get_state::<MyState>() {
    Ok(state) => println!("State value: {}", state.value),
    Err(err) => println!("Failed to get state: {:?}", err),
}
Examples found in repository?
examples/sovran_example.rs (line 59)
58
59
60
61
62
    fn check_balance(&self) -> f64 {
        self.store.get_state::<BankState>()
            .map(|state| state.balance)
            .unwrap_or(0.0)
    }
Source

pub fn dispatch<S: State, A: Action<S> + Send + 'static>( &self, action: A, ) -> Result<(), StoreError>

Dispatches an action to the store, affecting the state of a specific type.

§Arguments
  • action - An action that transforms the state.
§Returns

A Result indicating success or failure.

§Examples
use sovran_state::{Store, State, Action, StoreError};

#[derive(Clone, Debug)]
struct MyState {
    value: i32,
}

impl State for MyState {}

struct IncrementAction;

impl Action<MyState> for IncrementAction {
    fn reduce(&self, state: MyState) -> MyState {
        MyState { value: state.value + 1 }
    }
}

let store = Store::new();
store.provide(MyState { value: 0 }).unwrap();
match store.dispatch(IncrementAction) {
    Ok(_) => println!("Action dispatched successfully"),
    Err(err) => println!("Failed to dispatch action: {:?}", err),
}
Examples found in repository?
examples/sovran_example.rs (line 97)
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
fn main() {
    // Create store and provide initial state
    let store = Arc::new(Store::new());
    store.provide(BankState {
        balance: 1000.0,
        transaction_count: 0,
    }).expect("Failed to provide initial state");

    // Create our components
    let monitor = AccountMonitor::new(store.clone());
    let _logger = TransactionLogger::new(store.clone());

    println!("Initial balance: ${:.2}", monitor.check_balance());

    // Simulate some transactions
    println!("\nProcessing transactions...\n");

    // Deposit
    store.dispatch(DepositAction(500.0))
        .expect("Failed to process deposit");
    thread::sleep(Duration::from_millis(500));

    // Withdraw
    store.dispatch(WithdrawAction(200.0))
        .expect("Failed to process withdrawal");
    thread::sleep(Duration::from_millis(500));

    // Deposit again
    store.dispatch(DepositAction(750.0))
        .expect("Failed to process deposit");
    thread::sleep(Duration::from_millis(500));

    println!("\nFinal balance: ${:.2}", monitor.check_balance());
}
Source

pub fn subscribe<S: State, F: Fn(&S) + Send + Sync + 'static>( &self, callback: F, ) -> Result<SubscriberId, StoreError>

Subscribes to state changes of a specific type with a given callback.

§Arguments
  • callback - A callback function that will be invoked when the state changes.
§Returns

A Result containing the subscriber ID on success, or a StoreError on failure.

§Examples
use sovran_state::{Store, State, StoreError};

#[derive(Clone, Debug)]
struct MyState {
    value: i32,
}

impl State for MyState {}

let store = Store::new();
store.provide(MyState { value: 10 }).unwrap();
match store.subscribe(|state: &MyState| {
    println!("State changed: {:?}", state);
}) {
    Ok(subscriber_id) => println!("Subscribed with ID: {}", subscriber_id),
    Err(err) => println!("Failed to subscribe: {:?}", err),
}
Examples found in repository?
examples/sovran_example.rs (lines 51-53)
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
    fn new(store: Arc<Store>) -> Self {
        let monitor = AccountMonitor { store: store.clone() };

        // Subscribe to state changes
        monitor.store.subscribe(move |state: &BankState| {
            println!("🏦 Account Monitor: Balance changed to ${:.2}", state.balance);
        }).expect("Failed to subscribe to state changes");

        monitor
    }

    fn check_balance(&self) -> f64 {
        self.store.get_state::<BankState>()
            .map(|state| state.balance)
            .unwrap_or(0.0)
    }
}

impl TransactionLogger {
    fn new(store: Arc<Store>) -> Self {
        let logger = TransactionLogger { store: store.clone() };

        // Subscribe to state changes
        logger.store.subscribe(move |state: &BankState| {
            println!("📝 Transaction Logger: Transaction #{} processed",
                     state.transaction_count);
        }).expect("Failed to subscribe to state changes");

        logger
    }
Source

pub fn unsubscribe<S: State>(&self, id: SubscriberId) -> Result<(), StoreError>

Unsubscribes from state changes of a specific type using the given subscriber ID.

§Arguments
  • id - The ID of the subscriber to be removed.
§Returns

A Result indicating success or failure.

§Examples
use sovran_state::{Store, State, StoreError};

#[derive(Clone, Debug)]
struct MyState {
    value: i32,
}

impl State for MyState {}

let store = Store::new();
store.provide(MyState { value: 10 }).unwrap();
let id = store.subscribe(|state: &MyState| {
    println!("State changed: {:?}", state);
}).unwrap();
match store.unsubscribe::<MyState>(id) {
    Ok(_) => println!("Unsubscribed successfully"),
    Err(err) => println!("Failed to unsubscribe: {:?}", err),
}

Trait Implementations§

Source§

impl Clone for Store

Source§

fn clone(&self) -> Store

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

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

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl Freeze for Store

§

impl RefUnwindSafe for Store

§

impl Send for Store

§

impl Sync for Store

§

impl Unpin for Store

§

impl UnwindSafe for Store

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, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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.