intercomm

Crates.iointercomm
lib.rsintercomm
version0.1.1
sourcesrc
created_at2022-01-09 04:57:18.338902
updated_at2022-01-11 18:47:05.169994
descriptionAsynchronous inter-component communication library
homepage
repositoryhttps://github.com/bingo347/intercomm
max_upload_size
id510662
size43,093
Dmitry Belyaev (bingo347)

documentation

README

intercomm

Asynchronous inter-component communication library

Example

use intercomm::{broadcast, notification, request};

intercomm::declare! {
    request Sum((i32, i32)) -> i32;
    request Mul((i32, i32)) -> i32;

    notification[2] Ready(());
    broadcast[1] Close(());
}

async fn sum_listener() {
    let mut listener = request::listen::<Sum>().await.expect("Sum listen twice");
    let mut close = broadcast::subscribe::<Close>().await;
    Ready::notify(()).await.expect("Cannot send Ready");

    loop {
        tokio::select! {
            _ = close.recv() => {
                listener.close().await;
                close.close().await;
                return;
            }
            _ = listener.accept(|(a, b)| async move {
                println!("Sum requested with: ({}, {})", a, b);
                a + b
            }) => {}
        }
    }
}

async fn mul_listener() {
    let mut listener = request::listen::<Mul>().await.expect("Mul listen twice");
    let mut close = broadcast::subscribe::<Close>().await;
    Ready::notify(()).await.expect("Cannot send Ready");

    loop {
        tokio::select! {
            _ = close.recv() => {
                listener.close().await;
                close.close().await;
                return;
            }
            _ = listener.accept(|(a, b)| async move {
                println!("Mul requested with: ({}, {})", a, b);
                a * b
            }) => {}
        }
    }
}

#[tokio::main]
async fn main() {
    let mut ready = notification::subscribe::<Ready>()
        .await
        .expect("Ready subscribed twice");
    let sum_join = tokio::spawn(sum_listener());
    let mul_join = tokio::spawn(mul_listener());
    for _ in 0..2 {
        ready.recv().await;
    }
    ready.close().await;

    let sum = Sum::request((5, 10)).await.expect("Cannot request Sum");
    println!("5 + 10 = {}", sum);

    let mul = Mul::request((5, 10)).await.expect("Cannot request Mul");
    println!("5 * 10 = {}", mul);

    Close::notify(()).await;
    sum_join.await.expect("sum_listener panicked");
    mul_join.await.expect("mul_listener panicked");
}
Commit count: 33

cargo fmt