1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
//! Thread safe communication channels
use crate::queue::{NotificationError, Notifier};
use crate::NotificationId;
use crossbeam::channel as beamchannel;
use std::error;
use std::sync::{mpsc, Arc};
use std::{fmt, io};

/// Creates a new asynchronous/unbounded channel, where the `Sender::send` function, in addition to sending a message,
/// triggers a notification on `Poll`
pub fn channel<T>(
    notifier: Arc<dyn Notifier>,
    id: NotificationId,
) -> (Sender<T>, mpsc::Receiver<T>) {
    let (tx, rx) = mpsc::channel();
    let tx = Sender { notifier, tx, id };
    (tx, rx)
}

/// Creates a new synchronous channel, where the `SyncSender::send` function, in addition to sending a message,
/// triggers a notification on `Poll`
pub fn sync_channel<T>(
    notifier: Arc<dyn Notifier>,
    id: NotificationId,
    bound_size: usize,
) -> (SyncSender<T>, mpsc::Receiver<T>) {
    let (tx, rx) = mpsc::sync_channel(bound_size);
    let tx = SyncSender { notifier, tx, id };
    (tx, rx)
}

/// Creates a new asynchronous/unbounded crossbeam channel, where the `Sender::send` function, in addition to sending a message,
/// triggers a notification on `Poll`
pub fn crossbeam_channel_unbounded<T>(
    notifier: Arc<dyn Notifier>,
    id: NotificationId,
) -> (CrossbeamSender<T>, beamchannel::Receiver<T>) {
    let (tx, rx) = beamchannel::unbounded();
    let tx = CrossbeamSender { notifier, tx, id };
    (tx, rx)
}

/// Creates a new synchronous/bounded crossbeam channel, where the `Sender::send` function, in addition to sending a message,
/// triggers a notification on `Poll`
pub fn crossbeam_channel_bounded<T>(
    notifier: Arc<dyn Notifier>,
    id: NotificationId,
    size: usize,
) -> (CrossbeamSender<T>, beamchannel::Receiver<T>) {
    let (tx, rx) = beamchannel::bounded(size);
    let tx = CrossbeamSender { notifier, tx, id };
    (tx, rx)
}

/// The sending half of a channel.
pub struct Sender<T> {
    tx: mpsc::Sender<T>,
    notifier: Arc<dyn Notifier>,
    id: NotificationId,
}

impl<T> Sender<T> {
    /// Attempts to send a value on this channel, returning it back if it could not be sent.
    pub fn send(&self, t: T) -> Result<(), SendError<T>> {
        self.tx.send(t).map_err(SendError::from)?;
        self.notifier.notify(self.id).map_err(SendError::from)
    }
}

/// The sending half of a channel crossbeam channel
pub struct CrossbeamSender<T> {
    tx: beamchannel::Sender<T>,
    notifier: Arc<dyn Notifier>,
    id: NotificationId,
}

impl<T> CrossbeamSender<T> {
    /// Attempts to send a value on this channel, returning it back if it could not be sent.
    /// For bounded channels, it will block.
    pub fn send(&self, t: T) -> Result<(), SendError<T>> {
        self.tx.send(t).map_err(SendError::from)?;
        self.notifier.notify(self.id).map_err(SendError::from)
    }

    /// Attempts to send a value on this channel without blocking.
    ///
    /// This method differs from `send` by returning immediately if the channel's
    /// buffer is full or no receiver is waiting to acquire some data.
    pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
        self.tx
            .try_send(t)
            .map_err(From::from)
            .and_then(|_| self.notifier.notify(self.id).map_err(From::from))
    }
}

/// The sending half of a synchronous channel.
pub struct SyncSender<T> {
    tx: mpsc::SyncSender<T>,
    notifier: Arc<dyn Notifier>,
    id: NotificationId,
}

impl<T> SyncSender<T> {
    /// Sends a value on this synchronous channel.
    ///
    /// This function will *block* until space in the internal buffer becomes
    /// available or a receiver is available to hand off the message to.
    pub fn send(&self, t: T) -> Result<(), SendError<T>> {
        self.tx
            .send(t)
            .map_err(From::from)
            .and_then(|_| self.notifier.notify(self.id).map_err(From::from))
    }

    /// Attempts to send a value on this channel without blocking.
    ///
    /// This method differs from `send` by returning immediately if the channel's
    /// buffer is full or no receiver is waiting to acquire some data.
    pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
        self.tx
            .try_send(t)
            .map_err(From::from)
            .and_then(|_| self.notifier.notify(self.id).map_err(From::from))
    }
}

/// An error returned from the `Sender::send`
pub enum SendError<T> {
    /// An IO error.
    Io(io::Error),

    /// The receiving half of the channel has disconnected.
    Disconnected(T),

    /// Underlying notification queue is full
    NotificationQueueFull,
}

/// An error returned from the `SyncSender::try_send` function.
pub enum TrySendError<T> {
    /// An IO error.
    Io(io::Error),

    /// Data could not be sent over the channel because it would require the callee to block.
    Full(T),

    /// The receiving half of the channel has disconnected.
    Disconnected(T),

    /// Underlying notification queue is full
    NotificationQueueFull,
}

impl<T> Clone for Sender<T> {
    fn clone(&self) -> Sender<T> {
        Sender {
            tx: self.tx.clone(),
            notifier: Arc::clone(&self.notifier),
            id: self.id,
        }
    }
}

impl<T> Clone for SyncSender<T> {
    fn clone(&self) -> SyncSender<T> {
        SyncSender {
            tx: self.tx.clone(),
            notifier: Arc::clone(&self.notifier),
            id: self.id,
        }
    }
}

/*
 *
 * ===== Implement Error conversions =====
 *
 */

impl<T> From<mpsc::SendError<T>> for SendError<T> {
    fn from(src: mpsc::SendError<T>) -> Self {
        SendError::Disconnected(src.0)
    }
}

impl<T> From<io::Error> for SendError<T> {
    fn from(src: io::Error) -> Self {
        SendError::Io(src)
    }
}

impl<T> From<beamchannel::SendError<T>> for SendError<T> {
    fn from(src: beamchannel::SendError<T>) -> Self {
        SendError::Disconnected(src.0)
    }
}

impl<T> From<NotificationError<NotificationId>> for SendError<T> {
    fn from(_: NotificationError<NotificationId>) -> Self {
        SendError::NotificationQueueFull
    }
}

impl<T> From<mpsc::TrySendError<T>> for TrySendError<T> {
    fn from(src: mpsc::TrySendError<T>) -> Self {
        match src {
            mpsc::TrySendError::Full(v) => TrySendError::Full(v),
            mpsc::TrySendError::Disconnected(v) => TrySendError::Disconnected(v),
        }
    }
}

impl<T> From<NotificationError<NotificationId>> for TrySendError<T> {
    fn from(_: NotificationError<NotificationId>) -> Self {
        TrySendError::NotificationQueueFull
    }
}

impl<T> From<beamchannel::TrySendError<T>> for TrySendError<T> {
    fn from(src: beamchannel::TrySendError<T>) -> Self {
        match src {
            beamchannel::TrySendError::Full(v) => TrySendError::Full(v),
            beamchannel::TrySendError::Disconnected(v) => TrySendError::Disconnected(v),
        }
    }
}

impl<T> From<mpsc::SendError<T>> for TrySendError<T> {
    fn from(src: mpsc::SendError<T>) -> Self {
        TrySendError::Disconnected(src.0)
    }
}

impl<T> From<io::Error> for TrySendError<T> {
    fn from(src: io::Error) -> Self {
        TrySendError::Io(src)
    }
}

/*
 *
 * ===== Implement Error, Debug, and Display for Errors =====
 *
 */

impl<T> error::Error for SendError<T> {}

impl<T> error::Error for TrySendError<T> {}

impl<T> fmt::Debug for SendError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SendError::Io(io_err) => write!(f, "{:?}", io_err),
            SendError::Disconnected(_) => write!(f, "Disconnected(..)"),
            SendError::NotificationQueueFull => write!(f, "NotificationQueueFull"),
        }
    }
}

impl<T> fmt::Display for SendError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SendError::Io(io_err) => write!(f, "{}", io_err),
            SendError::Disconnected(_) => write!(f, "sending on a closed channel"),
            SendError::NotificationQueueFull => write!(f, "sending on a full notification queue"),
        }
    }
}

impl<T> fmt::Debug for TrySendError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TrySendError::Io(io_err) => write!(f, "{:?}", io_err),
            TrySendError::Full(..) => write!(f, "Full(..)"),
            TrySendError::Disconnected(..) => write!(f, "Disconnected(..)"),
            TrySendError::NotificationQueueFull => write!(f, "NotificationQueueFull"),
        }
    }
}

impl<T> fmt::Display for TrySendError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TrySendError::Io(io_err) => write!(f, "{}", io_err),
            TrySendError::Full(..) => write!(f, "sending on a full channel"),
            TrySendError::Disconnected(..) => write!(f, "sending on a closed channel"),
            TrySendError::NotificationQueueFull => {
                write!(f, "sending on a full notification queue")
            }
        }
    }
}