ckb_channel/
lib.rs

1//! Reexports `crossbeam_channel` to uniform the dependency version.
2pub use crossbeam_channel::{
3    Receiver, RecvError, RecvTimeoutError, Select, SendError, Sender, TrySendError, after, bounded,
4    select, tick, unbounded,
5};
6
7pub mod oneshot {
8    //! A one-shot channel is used for sending a single message between asynchronous tasks.
9
10    use std::sync::mpsc::sync_channel;
11    pub use std::sync::mpsc::{Receiver, RecvError, SyncSender as Sender};
12
13    /// Create a new one-shot channel for sending single values across asynchronous tasks.
14    pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
15        sync_channel(1)
16    }
17}
18
19/// Default channel size to send control signals.
20pub const SIGNAL_CHANNEL_SIZE: usize = 1;
21/// Default channel size to send messages.
22pub const DEFAULT_CHANNEL_SIZE: usize = 32;
23
24/// Synchronous request sent to the service.
25pub struct Request<A, R> {
26    /// One shot channel for the service to send back the response.
27    pub responder: oneshot::Sender<R>,
28    /// Request arguments.
29    pub arguments: A,
30}
31
32impl<A, R> Request<A, R> {
33    /// Call the service with the arguments and wait for the response.
34    pub fn call(sender: &Sender<Request<A, R>>, arguments: A) -> Option<R> {
35        let (responder, response) = oneshot::channel();
36        let _ = sender.send(Request {
37            responder,
38            arguments,
39        });
40        response.recv().ok()
41    }
42}