Trait wnf::AsState

source ·
pub trait AsState: Sealed {
    type Data: ?Sized;

    fn as_state(&self) -> BorrowedState<'_, Self::Data>;
}
Expand description

A trait for types that can be borrowed as a state

This is implemented for both OwnedState<T> and BorrowedState<'_, T>. There are two main use cases for it:

  • Functions that can accept either a reference to an owned or a borrowed state: Even though a BorrowedState<'_, T> plays the role of a reference to a state, it’s not technically a reference. As a consequence, there is no deref coercion for states, i.e. you cannot just pass an &'a OwnedState<T> where a BorrowedState<'a, T> is expected. In order to accept both types, functions can instead take a reference to a generic type implementing AsState:
fn add_to_state(state: &impl AsState<Data = u32>, delta: u32) -> io::Result<()> {
    let state = state.as_state();
    let value = state.get()?;
    let new_value = value + delta;
    state.set(&new_value)
}
  • Types that can contain either an owned or a borrowed state:
struct StateWrapper<S> {
    state: S,
}

impl<S> StateWrapper<S>
where
    S: AsState<Data = u32>,
{
    fn add(&self, delta: u32) -> io::Result<()> {
        let state = self.state.as_state();
        let value = state.get()?;
        let new_value = value + delta;
        state.set(&new_value)
    }
}

When comparing OwnedState<T> with OwnedHandle and BorrowedState<'_, T> with BorrowedHandle<'_>, this trait plays the role of the AsHandle trait.

This trait is sealed and cannot by implemented outside of the wnf crate.

Required Associated Types§

The type of the data contained in the borrowed state

Required Methods§

Borrows a value as a state

Implementors§