Documentation
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use futures::{Sink, SinkExt, Stream, StreamExt};

use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::task::{Context, Poll};

pub use queue_ext::SendError;
#[allow(unused_imports)]
use queue_ext::{Action, QueueExt, Reply, Waker};

///BinaryHeap based channel
#[cfg(feature = "priority")]
#[allow(clippy::type_complexity)]
pub fn with_priority_channel<P: Ord + 'static, T: 'static>(
    queue: std::sync::Arc<std_ext::RwLock<collections::PriorityQueue<P, T>>>,
    bound: usize,
) -> (Sender<(P, T), SendError<(P, T)>>, Receiver<(P, T)>) {
    let (tx, rx) = queue.queue_channel::<_, _, _, _>(
        move |s, act| match act {
            Action::Send((p, val)) => {
                s.write().push(p, val);
                Reply::Send(())
            }
            Action::IsFull => Reply::IsFull(s.read().len() >= bound),
            Action::IsEmpty => Reply::IsEmpty(s.read().is_empty()),
            Action::Len => Reply::Len(s.read().len()),
        },
        |s, _| {
            let mut s = s.write();
            match s.pop() {
                Some(m) => Poll::Ready(Some(m)),
                None => Poll::Pending,
            }
        },
    );

    (Sender::new(tx), Receiver::new(rx))
}

///BinaryHeap based channel
#[cfg(feature = "priority")]
#[allow(clippy::type_complexity)]
pub fn priority_channel<P: 'static + Ord, T: 'static>(
    bound: usize,
) -> (Sender<(P, T), SendError<(P, T)>>, Receiver<(P, T)>) {
    use collections::PriorityQueue;
    use std_ext::{ArcExt, RwLockExt};
    let queue = PriorityQueue::default().rwlock().arc();
    with_priority_channel(queue, bound)
}

///SegQueue based channel
#[cfg(feature = "segqueue")]
pub fn with_segqueue_channel<T: 'static>(
    queue: std::sync::Arc<crossbeam_queue::SegQueue<T>>,
    bound: usize,
) -> (Sender<T, SendError<T>>, Receiver<T>) {
    let (tx, rx) = queue.queue_channel::<T, _, _, _>(
        move |s, act| match act {
            Action::Send(val) => {
                s.push(val);
                Reply::Send(())
            }
            Action::IsFull => Reply::IsFull(s.len() >= bound),
            Action::IsEmpty => Reply::IsEmpty(s.is_empty()),
            Action::Len => Reply::Len(s.len()),
        },
        |s, _| match s.pop() {
            Some(m) => Poll::Ready(Some(m)),
            None => Poll::Pending,
        },
    );
    (Sender::new(tx), Receiver::new(rx))
}

///SegQueue based channel
#[cfg(feature = "segqueue")]
pub fn segqueue_channel<T: 'static>(bound: usize) -> (Sender<T, SendError<T>>, Receiver<T>) {
    use crossbeam_queue::SegQueue;
    use std_ext::ArcExt;
    with_segqueue_channel(SegQueue::default().arc(), bound)
}

///VecDeque based channel
#[cfg(feature = "vecdeque")]
pub fn with_vecdeque_channel<T: 'static>(
    queue: std::sync::Arc<std_ext::RwLock<std::collections::VecDeque<T>>>,
    bound: usize,
) -> (Sender<T, SendError<T>>, Receiver<T>) {
    let (tx, rx) = queue.queue_channel::<T, _, _, _>(
        move |s, act| match act {
            Action::Send(val) => {
                s.write().push_back(val);
                Reply::Send(())
            }
            Action::IsFull => Reply::IsFull(s.read().len() >= bound),
            Action::IsEmpty => Reply::IsEmpty(s.read().is_empty()),
            Action::Len => Reply::Len(s.read().len()),
        },
        |s, _| {
            let mut s = s.write();
            match s.pop_front() {
                Some(m) => Poll::Ready(Some(m)),
                None => Poll::Pending,
            }
        },
    );
    (Sender::new(tx), Receiver::new(rx))
}

///VecDeque based channel
#[cfg(feature = "vecdeque")]
pub fn vecdeque_channel<T: 'static>(bound: usize) -> (Sender<T, SendError<T>>, Receiver<T>) {
    use std::collections::VecDeque;
    use std_ext::{ArcExt, RwLockExt};
    let queue = VecDeque::default().rwlock().arc();
    with_vecdeque_channel(queue, bound)
}

///Indexmap based channel, remove entry if it already exists
#[cfg(feature = "indexmap")]
#[allow(clippy::type_complexity)]
pub fn with_indexmap_channel<K, T>(
    indexmap: std::sync::Arc<std_ext::RwLock<indexmap::IndexMap<K, T>>>,
    bound: usize,
) -> (Sender<(K, T), SendError<(K, T)>>, Receiver<(K, T)>)
where
    K: Eq + std::hash::Hash + 'static,
    T: 'static,
{
    let (tx, rx) = indexmap.queue_channel::<(K, T), _, _, _>(
        move |s, act| match act {
            Action::Send((key, val)) => {
                let mut s = s.write();
                //Remove this entry if it already exists
                let reply = s.insert(key, val);
                Reply::Send(reply)
            }
            Action::IsFull => Reply::IsFull(s.read().len() >= bound),
            Action::IsEmpty => Reply::IsEmpty(s.read().is_empty()),
            Action::Len => Reply::Len(s.read().len()),
        },
        |s, _| {
            let mut s = s.write();
            match s.pop() {
                Some(m) => Poll::Ready(Some(m)),
                None => Poll::Pending,
            }
        },
    );
    (Sender::new(tx), Receiver::new(rx))
}

///Indexmap based channel, remove entry if it already exists
#[cfg(feature = "indexmap")]
#[allow(clippy::type_complexity)]
pub fn indexmap_channel<K, T>(bound: usize) -> (Sender<(K, T), SendError<(K, T)>>, Receiver<(K, T)>)
where
    K: Eq + std::hash::Hash + 'static,
    T: 'static,
{
    use indexmap::IndexMap;
    use std_ext::{ArcExt, RwLockExt};
    let map = IndexMap::new().rwlock().arc();
    with_indexmap_channel(map, bound)
}

pub trait SenderSink<M, E>: futures::Sink<M, Error = E> + Unpin + Send + Sync {
    fn box_clone(&self) -> Box<dyn SenderSink<M, E>>;
}

impl<T, M, E> SenderSink<M, E> for T
where
    T: futures::Sink<M, Error = E> + Unpin + Send + Sync + 'static,
    T: Clone,
{
    #[inline]
    fn box_clone(&self) -> Box<dyn SenderSink<M, E>> {
        Box::new(self.clone())
    }
}

pub struct Sender<M, E> {
    tx: Box<dyn SenderSink<M, E>>,
}

impl<M, E> Sender<M, E> {
    #[inline]
    pub fn new<T>(tx: T) -> Self
    where
        T: Sink<M, Error = E> + Sync + Send + Unpin + 'static,
        T: Clone,
    {
        Sender { tx: Box::new(tx) }
    }

    #[inline]
    pub async fn send(&mut self, t: M) -> std::result::Result<(), E> {
        self.tx.send(t).await
    }
}

impl<M, E> Clone for Sender<M, E> {
    #[inline]
    fn clone(&self) -> Self {
        Sender {
            tx: self.tx.box_clone(),
        }
    }
}

impl<M, E> Deref for Sender<M, E> {
    type Target = Box<dyn SenderSink<M, E>>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.tx
    }
}

impl<M, E> DerefMut for Sender<M, E> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.tx
    }
}

impl<M, E> futures::Sink<M> for Sender<M, E> {
    type Error = E;

    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.tx).poll_ready(cx)
    }

    fn start_send(mut self: Pin<&mut Self>, msg: M) -> Result<(), Self::Error> {
        Pin::new(&mut self.tx).start_send(msg)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.tx).poll_flush(cx)
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.tx).poll_close(cx)
    }
}

pub trait ReceiverStream<M>: futures::Stream<Item = M> + Send + Sync + Unpin + Waker {}

impl<T, M> ReceiverStream<M> for T where
    T: futures::Stream<Item = M> + Send + Sync + Unpin + Waker + 'static
{
}

pub struct Receiver<M> {
    rx: Box<dyn ReceiverStream<M>>,
}

impl<M> Drop for Receiver<M> {
    fn drop(&mut self) {
        self.rx.close_channel();
    }
}

impl<M> Receiver<M> {
    #[inline]
    pub fn new<T>(tx: T) -> Self
    where
        T: futures::Stream<Item = M> + Send + Sync + Unpin + Waker + 'static,
    {
        Receiver { rx: Box::new(tx) }
    }

    #[inline]
    pub async fn recv(&mut self) -> Option<M> {
        self.rx.next().await
    }

    #[inline]
    pub fn is_closed(&self) -> bool {
        self.rx.is_closed()
    }
}

impl<M> Deref for Receiver<M> {
    type Target = Box<dyn ReceiverStream<M>>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.rx
    }
}

impl<M> DerefMut for Receiver<M> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.rx
    }
}

impl<M> Stream for Receiver<M> {
    type Item = M;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.rx).poll_next(cx)
    }
}

pub trait LocalSenderSink<M, E>: futures::Sink<M, Error = E> + Unpin {
    fn box_clone(&self) -> Box<dyn LocalSenderSink<M, E>>;
}

impl<T, M, E> LocalSenderSink<M, E> for T
where
    T: futures::Sink<M, Error = E> + Unpin + 'static,
    T: Clone,
{
    #[inline]
    fn box_clone(&self) -> Box<dyn LocalSenderSink<M, E>> {
        Box::new(self.clone())
    }
}

pub struct LocalSender<M, E> {
    tx: Box<dyn LocalSenderSink<M, E>>,
}

//unsafe impl<M, E> Sync for LocalSender<M, E> {}

impl<M, E> LocalSender<M, E> {
    #[inline]
    pub fn new<T>(tx: T) -> Self
    where
        T: Sink<M, Error = E> + Unpin + 'static,
        T: Clone,
    {
        LocalSender { tx: Box::new(tx) }
    }

    #[inline]
    pub async fn send(&mut self, t: M) -> std::result::Result<(), E> {
        self.tx.send(t).await
    }
}

impl<M, E> Clone for LocalSender<M, E> {
    #[inline]
    fn clone(&self) -> Self {
        LocalSender {
            tx: self.tx.box_clone(),
        }
    }
}

impl<M, E> Deref for LocalSender<M, E> {
    type Target = Box<dyn LocalSenderSink<M, E>>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.tx
    }
}

impl<M, E> DerefMut for LocalSender<M, E> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.tx
    }
}

impl<M, E> futures::Sink<M> for LocalSender<M, E> {
    type Error = E;

    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.tx).poll_ready(cx)
    }

    fn start_send(mut self: Pin<&mut Self>, msg: M) -> Result<(), Self::Error> {
        Pin::new(&mut self.tx).start_send(msg)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.tx).poll_flush(cx)
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.tx).poll_close(cx)
    }
}

pub trait LocalReceiverStream<M>: futures::Stream<Item = M> + Unpin {}

impl<T, M> LocalReceiverStream<M> for T where T: futures::Stream<Item = M> + Unpin + 'static {}

pub struct LocalReceiver<M> {
    rx: Box<dyn LocalReceiverStream<M>>,
}

impl<M> LocalReceiver<M> {
    #[inline]
    pub fn new<T>(tx: T) -> Self
    where
        T: futures::Stream<Item = M> + Unpin + 'static,
    {
        LocalReceiver { rx: Box::new(tx) }
    }

    #[inline]
    pub async fn recv(&mut self) -> Option<M> {
        self.rx.next().await
    }
}

impl<M> Deref for LocalReceiver<M> {
    type Target = Box<dyn LocalReceiverStream<M>>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.rx
    }
}

impl<M> DerefMut for LocalReceiver<M> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.rx
    }
}

impl<M> Stream for LocalReceiver<M> {
    type Item = M;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.rx).poll_next(cx)
    }
}