Struct asynchron::SyncState[][src]

pub struct SyncState<T> { /* fields omitted */ }
Expand description

Tricky oneshot thread safe state management

WARNING! (if not sure how to use it, don’t use it)

using std::sync::Arc, std::sync::Mutex and core::option::Option under the hood.

Example:

use asynchron::SyncState;

fn main() -> core::result::Result<(), Box<dyn std::error::Error>> {
    let state: SyncState<i32> = SyncState::new(0);
    let _state = state.clone();
    
    // The state will be empty if it successfully loaded.
    match state.load() {
        Some(value) => {
            println!("initial value: {:?}", value)
        }
        _ => (),
    }
    
    assert_eq!(true, state.is_empty());

    if let Err(_) = std::thread::spawn(move || {
        if _state.is_empty() {
            // Restore the state.
            _state.store(20)
        }
    })
    .join()
    {
        let e = std::io::Error::new(std::io::ErrorKind::Other, "Unable to join the thread.");
        return Err(Box::new(e));
    }

    if state.is_full() {
        match state.load() {
            Some(value) => {
                assert_eq!(value, 20);
                println!("latest value {:?}", value)
            }
            _ => {
                let e = std::io::Error::new(std::io::ErrorKind::Other, "State not restore.");
                return Err(Box::new(e));
            }
        }
    }
    
    assert_eq!(true, state.is_empty());
    
    Ok(())
}

Implementations

Create new state.

Load new value from the state.

Store new value to the state

Check if the state isn’t full (if it isn’t full, just store it).

Check if the state isn’t empty (if it isn’t empty, just load it).

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

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

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.