homestar_runtime/
channel.rs

1//! Wrapper around [crossbeam::channel] and [flume] to provide common
2//! interfaces for sync/async (un)bounded and non-tokio oneshot channels.
3
4use crossbeam::channel;
5
6/// Sender for a bounded [crossbeam::channel].
7pub type BoundedChannelSender<T> = channel::Sender<T>;
8
9/// Receiver for a bounded [crossbeam::channel].
10pub type BoundedChannelReceiver<T> = channel::Receiver<T>;
11
12/// A bounded [crossbeam::channel] with a sender and receiver.
13#[allow(dead_code)]
14#[derive(Debug, Clone)]
15pub struct Channel<T> {
16    /// Sender for the channel.
17    tx: channel::Sender<T>,
18    /// REceiver for the channel.
19    rx: channel::Receiver<T>,
20}
21
22impl<T> Channel<T> {
23    /// Create a new [Channel] with a given capacity.
24    pub fn with(capacity: usize) -> (BoundedChannelSender<T>, BoundedChannelReceiver<T>) {
25        let (tx, rx) = channel::bounded(capacity);
26        (tx, rx)
27    }
28
29    /// Create a oneshot (1) [Channel].
30    pub fn oneshot() -> (BoundedChannelSender<T>, BoundedChannelReceiver<T>) {
31        let (tx, rx) = channel::bounded(1);
32        (tx, rx)
33    }
34}
35
36/// [flume::Sender] for a bounded [flume::bounded] channel.
37pub type AsyncChannelSender<T> = flume::Sender<T>;
38
39/// [flume::Receiver] for a bounded [flume::bounded] channel.
40pub type AsyncChannelReceiver<T> = flume::Receiver<T>;
41
42/// A bounded [flume] channel with sender and receiver.
43#[allow(dead_code)]
44#[derive(Debug, Clone)]
45pub struct AsyncChannel<T> {
46    /// Sender for the channel.
47    tx: flume::Sender<T>,
48    /// REceiver for the channel.
49    rx: flume::Receiver<T>,
50}
51
52impl<T> AsyncChannel<T> {
53    /// Create a new [AsyncChannel] with a given capacity.
54    pub fn with(capacity: usize) -> (AsyncChannelSender<T>, AsyncChannelReceiver<T>) {
55        let (tx, rx) = flume::bounded(capacity);
56        (tx, rx)
57    }
58
59    /// Create an unbounded [AsyncChannel].
60    pub fn unbounded() -> (AsyncChannelSender<T>, AsyncChannelReceiver<T>) {
61        let (tx, rx) = flume::unbounded();
62        (tx, rx)
63    }
64
65    /// Create a oneshot (1) [Channel].
66    pub fn oneshot() -> (AsyncChannelSender<T>, AsyncChannelReceiver<T>) {
67        let (tx, rx) = flume::bounded(1);
68        (tx, rx)
69    }
70}