1 个不稳定版本
0.1.2 | 2023 年 5 月 2 日 |
---|---|
0.1.1 |
|
0.1.0 |
|
#18 in #facilitate
每月 25 次下载
7KB
59 行
linkk
关于
此 crate 提供了一种简单的方法来创建一组通道并将它们交叉。这种模式对于使难以相互通信的事物进行通信非常有用。
从概念上讲,可以将其视为建立一座桥梁,并且可以使用它通过通道发送任何类型的数据。
几乎肯定有更优雅的方法来做这件事...但我不知道那是什么。
安装
将此添加到您的 Cargo.toml 中
[dependencies]
linkk = "0.1.2"
用法
以下是如何使用此 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
:
此 crate 非常简单,它创建一组通道并将它们交叉。
我发现最近自己经常使用这种模式来让难以相互交谈的事物相互交谈。可能有一种更好的方法--但我不知道。
从概念上讲,我认为它就像建一座桥梁一样,不需要发送相同的 <T>
,实际上你可以在里面放各种各样的东西...我知道,我这么做了。
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);
这应该能帮你省去以下所有这些替代方案
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 };
}
请参阅测试以了解示例用法。
依赖项
~270–730KB
~17K SLoC