#channel #facilitate #parts #communication #different #crossing #send

linkk

A crate for creating channels and crossing them to facilitate communication between different parts of a program

1 unstable release

0.1.2 May 2, 2023
0.1.1 May 2, 2023
0.1.0 Apr 27, 2023

#17 in #facilitate

46 downloads per month

MIT license

7KB
59 lines

linkk

About:

This crate provides a simple way to make a set of channels and criss-cross them. This pattern is useful for getting things that are hard to get talking to each other to communicate.

Conceptually, it can be thought of as making a bridge, and it can be used to send any type of data across the channels.

There's almost certainly a nicer way of doing this... but, I dunno what that is.

Installation

Add this to your Cargo.toml:

[dependencies]
linkk = "0.1.2"

Usage:

Here is an example of how to use this crate:

use linkk::*;

setup_linkk!(pub, Window2os<u32>, Os2Window<u64>);

    let (link2, link1) = make_new_linkk();

    // link2 receives from link1
    link2.send(42).unwrap();
    assert_eq!(link1.recv().unwrap(), 42u32);

    // link1 receives from link2
    link1.tx.send(43 as u64).unwrap();
    assert_eq!(link2.rx.recv().unwrap(), 43);

lib.rs:

This crate is real simple, if makes a set of channels and criss-crosses them.

I find myself using this pattern a bit lately to get... things that're hard to get talking to eachother talking to eachother. There is probably a better way -- but, I don't know it.

Conceptually, I think of it as making a bridge, it needn't send the same <T> across, infact you can put all sorts of things in there.. I know, I have.

use linkk;
linkk::setup_linkk!(pub, Window2os<u32>, Os2Window<u64>);

let (w2os, os2w) = make_new_linkk();
// link2 receives from link1
w2os.send(42).unwrap();
assert_eq!(os2w.recv().unwrap(), 42u32);

// link1 receives from link2
os2w.tx.send(43 as u64).unwrap();
assert_eq!(w2os.rx.recv().unwrap(), 43);

Which should save you typing that alernative which would be all this:

pub struct Link1 {
   tx: std::sync::mpsc::Sender<u32>,
   rx: std::sync::mpsc::Receiver<u64>,
}
pub struct Link2 {
   tx: std::sync::mpsc::Sender<u64>,
   rx: std::sync::mpsc::Receiver<u32>,
}
impl Link1 {
   fn send(&self, t: u32) -> std::result::Result<(), std::sync::mpsc::SendError<u32>> {
       self.tx.send(t)
   }

   fn recv(&self) -> Result<u64, std::sync::mpsc::RecvError> {
       self.rx.recv()
   }
}

impl Link2 {
   fn send(&self, t: u64) -> std::result::Result<(), std::sync::mpsc::SendError<u64>> {
       self.tx.send(t)
   }

   fn recv(&self) -> Result<u32, std::sync::mpsc::RecvError> {
       self.rx.recv()
   }
}
fn init() {
   let (tx1, rx1) = std::sync::mpsc::channel::<u32>();
   let (tx2, rx2) = std::sync::mpsc::channel::<u64>();

   let link1 = Link1 { tx: tx1, rx: rx2 };
   let link2 = Link2 { tx: tx2, rx: rx1 };
}

See the tests for example usage.

Dependencies

~325–790KB
~19K SLoC