Trait PortMutex

Source
pub trait PortMutex {
    type Port;

    // Required methods
    fn create(v: Self::Port) -> Self;
    fn lock<R, F: FnOnce(&mut Self::Port) -> R>(&self, f: F) -> R;
}
Expand description

Common interface for mutex implementations.

port-expander needs a mutex to ensure only a single pin object can access the port-expander at the same time, in concurrent situations. port-expander already implements this trait for a number of existing mutex types. Most of them are guarded by a feature that needs to be enabled. Here is an overview:

MutexFeature NameNotes
core::cell::RefCellalways availableFor sharing within a single execution context.
std::sync::MutexstdFor platforms where std is available.
critical_section::Mutexcritical-sectionUse critical sections to ensure synchronized access, via the critical-section crate.

For other mutex types, a custom implementation is needed. Due to the orphan rule, it might be necessary to wrap it in a newtype. As an example, this is what such a custom implementation might look like:

struct MyMutex<T>(std::sync::Mutex<T>);

impl<T> port_expander::PortMutex for MyMutex<T> {
    type Port = T;

    fn create(v: T) -> Self {
        Self(std::sync::Mutex::new(v))
    }

    fn lock<R, F: FnOnce(&mut Self::Port) -> R>(&self, f: F) -> R {
        let mut v = self.0.lock().unwrap();
        f(&mut v)
    }
}

Required Associated Types§

Source

type Port

The actual port-expander that is wrapped inside this mutex.

Required Methods§

Source

fn create(v: Self::Port) -> Self

Create a new mutex of this type.

Source

fn lock<R, F: FnOnce(&mut Self::Port) -> R>(&self, f: F) -> R

Lock the mutex and give a closure access to the port-expander inside.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> PortMutex for RefCell<T>

Source§

type Port = T

Source§

fn create(v: Self::Port) -> Self

Source§

fn lock<R, F: FnOnce(&mut Self::Port) -> R>(&self, f: F) -> R

Implementors§