Store

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)
79fn main() {
80    // Create store and provide initial state
81    let store = Arc::new(Store::new());
82    store.provide(BankState {
83        balance: 1000.0,
84        transaction_count: 0,
85    }).expect("Failed to provide initial state");
86
87    // Create our components
88    let monitor = AccountMonitor::new(store.clone());
89    let _logger = TransactionLogger::new(store.clone());
90
91    println!("Initial balance: ${:.2}", monitor.check_balance());
92
93    // Simulate some transactions
94    println!("\nProcessing transactions...\n");
95
96    // Deposit
97    store.dispatch(DepositAction(500.0))
98        .expect("Failed to process deposit");
99    thread::sleep(Duration::from_millis(500));
100
101    // Withdraw
102    store.dispatch(WithdrawAction(200.0))
103        .expect("Failed to process withdrawal");
104    thread::sleep(Duration::from_millis(500));
105
106    // Deposit again
107    store.dispatch(DepositAction(750.0))
108        .expect("Failed to process deposit");
109    thread::sleep(Duration::from_millis(500));
110
111    println!("\nFinal balance: ${:.2}", monitor.check_balance());
112}
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)
79fn main() {
80    // Create store and provide initial state
81    let store = Arc::new(Store::new());
82    store.provide(BankState {
83        balance: 1000.0,
84        transaction_count: 0,
85    }).expect("Failed to provide initial state");
86
87    // Create our components
88    let monitor = AccountMonitor::new(store.clone());
89    let _logger = TransactionLogger::new(store.clone());
90
91    println!("Initial balance: ${:.2}", monitor.check_balance());
92
93    // Simulate some transactions
94    println!("\nProcessing transactions...\n");
95
96    // Deposit
97    store.dispatch(DepositAction(500.0))
98        .expect("Failed to process deposit");
99    thread::sleep(Duration::from_millis(500));
100
101    // Withdraw
102    store.dispatch(WithdrawAction(200.0))
103        .expect("Failed to process withdrawal");
104    thread::sleep(Duration::from_millis(500));
105
106    // Deposit again
107    store.dispatch(DepositAction(750.0))
108        .expect("Failed to process deposit");
109    thread::sleep(Duration::from_millis(500));
110
111    println!("\nFinal balance: ${:.2}", monitor.check_balance());
112}
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    fn check_balance(&self) -> f64 {
59        self.store.get_state::<BankState>()
60            .map(|state| state.balance)
61            .unwrap_or(0.0)
62    }
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)
79fn main() {
80    // Create store and provide initial state
81    let store = Arc::new(Store::new());
82    store.provide(BankState {
83        balance: 1000.0,
84        transaction_count: 0,
85    }).expect("Failed to provide initial state");
86
87    // Create our components
88    let monitor = AccountMonitor::new(store.clone());
89    let _logger = TransactionLogger::new(store.clone());
90
91    println!("Initial balance: ${:.2}", monitor.check_balance());
92
93    // Simulate some transactions
94    println!("\nProcessing transactions...\n");
95
96    // Deposit
97    store.dispatch(DepositAction(500.0))
98        .expect("Failed to process deposit");
99    thread::sleep(Duration::from_millis(500));
100
101    // Withdraw
102    store.dispatch(WithdrawAction(200.0))
103        .expect("Failed to process withdrawal");
104    thread::sleep(Duration::from_millis(500));
105
106    // Deposit again
107    store.dispatch(DepositAction(750.0))
108        .expect("Failed to process deposit");
109    thread::sleep(Duration::from_millis(500));
110
111    println!("\nFinal balance: ${:.2}", monitor.check_balance());
112}
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. The callback will receive the current state of the type immediately.

§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    fn new(store: Arc<Store>) -> Self {
48        let monitor = AccountMonitor { store: store.clone() };
49
50        // Subscribe to state changes
51        monitor.store.subscribe(move |state: &BankState| {
52            println!("🏦 Account Monitor: Balance changed to ${:.2}", state.balance);
53        }).expect("Failed to subscribe to state changes");
54
55        monitor
56    }
57
58    fn check_balance(&self) -> f64 {
59        self.store.get_state::<BankState>()
60            .map(|state| state.balance)
61            .unwrap_or(0.0)
62    }
63}
64
65impl TransactionLogger {
66    fn new(store: Arc<Store>) -> Self {
67        let logger = TransactionLogger { store: store.clone() };
68
69        // Subscribe to state changes
70        logger.store.subscribe(move |state: &BankState| {
71            println!("📝 Transaction Logger: Transaction #{} processed",
72                     state.transaction_count);
73        }).expect("Failed to subscribe to state changes");
74
75        logger
76    }
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 duplicate 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, 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.