ufotofu 0.10.1

Abstractions for lazily consuming and producing sequences
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! A **S**ingle-**S**ender **S**ingle-**R**eceiver FIFO channel.
//!
//! The entrypoint to this module is the [`new_sssr`] function. You supply it with a [`Queue`], and it returns the two endpoints of the channel: a [`Sender`] and a [`Receiver`].
//!
//! Calling [`consume`](Consumer::consume) with a `Left` on the [`Sender`] results in the item being emitted on the [`Receiver`]. If the internal queue is full, the `consume` future remains pending until the [`Receiver`] has produced at least one item.
//!
//! Calling [`consume`](Consumer::consume) with a `Right` on the [`Sender`] results in the final value being emitted on the [`Receiver`] (though all previously sent items are delivered first).
//!
//!  Dropping the [`Sender`] or the [`Receiver`] does not actively notify the other endpoint about anything. But both endpoint kinds have synchronous methods for checking whether there other endpoint is still active.
//!
//! #### Example
//!
//! ```
//! use futures::join;
//! use ufotofu::prelude::*;
//! use ufotofu::channels::sssr::*;
//!
//! // Create the channel, using a queue of capacity two.
//! let (mut sender, mut receiver) = new_sssr(ufotofu::queues::new_fixed::<i16>(2));
//!
//! pollster::block_on(async {
//!     // A future sending three items to the channel, then closing.
//!     let send_things = async {
//!         assert!(sender.consume_item(300).await.is_ok());
//!         assert!(sender.consume_item(400).await.is_ok());
//!         assert!(sender.consume_item(500).await.is_ok());
//!         assert!(sender.consume_final(-17).await.is_ok());
//!     };
//!
//!     // A future receiving the items from the channel.
//!     let receive_things = async {
//!         assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
//!         assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
//!         assert_eq!(500, receiver.produce().await.unwrap().unwrap_left());
//!         assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
//!     };
//!
//!     // Concurrently send and receive the items. Concurrency is necessary, because
//!     // the number of transmitted items exceeds the maximum capacity of the queue we use.
//!     join!(receive_things, send_things);
//! });
//! ```

use core::{convert::Infallible, fmt};

use std::rc::Rc;

use either::Either::{self};

use crate::prelude::*;
use crate::queues::Queue;

use super::advanced::sssr::{Receiver as AdvancedReceiver, Sender as AdvancedSender, State};

/// Creates a new single-sender single-receiver channel in the form of a [`Sender`] and a [`Receiver`] endpoint, which communicate via the given [`Queue`].
///
/// #### Example
///
/// ```
/// use futures::join;
/// use ufotofu::prelude::*;
/// use ufotofu::channels::sssr::*;
///
/// // Create the channel, using a queue of capacity two.
/// let (mut sender, mut receiver) = new_sssr(ufotofu::queues::new_fixed::<i16>(2));
///
/// pollster::block_on(async {
///     // A future sending three items to the channel, then closing.
///     let send_things = async {
///         assert!(sender.consume_item(300).await.is_ok());
///         assert!(sender.consume_item(400).await.is_ok());
///         assert!(sender.consume_item(500).await.is_ok());
///         assert!(sender.consume_final(-17).await.is_ok());
///     };
///
///     // A future receiving the items from the channel.
///     let receive_things = async {
///         assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
///         assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
///         assert_eq!(500, receiver.produce().await.unwrap().unwrap_left());
///         assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
///     };
///
///     // Concurrently send and receive the items. Concurrency is necessary, because
///     // the number of transmitted items exceeds the maximum capacity of the queue we use.
///     join!(receive_things, send_things);
/// });
/// ```
pub fn new_sssr<Q: Queue, F>(queue: Q) -> (Sender<Q, F>, Receiver<Q, F>) where {
    let state = Rc::new(State::new(queue));
    let (s, r) = super::advanced::new_sssr(state);
    (Sender(s), Receiver(r))
}

/// An endpoint for sending items to an sssr channel (and for closing the channel).
///
/// Use the [`Consumer`] or [`BulkConsumer`] implementations to write data to the channel.
///
/// This type does *not* implement [`Clone`], making the channel a *single-sender* channel.
///
/// <br/>Counterpart: the [`Receiver`] type.
pub struct Sender<Q, F>(AdvancedSender<Rc<State<Q, F>>, Q, F>);

impl<Q, F> fmt::Debug for Sender<Q, F>
where
    Q: fmt::Debug,
    F: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<Q, F> Sender<Q, F>
where
    Q: Queue,
{
    /// Returns the number of items in the queue that buffers items for this channel.
    ///
    /// Note that this method only considers regular items — whether the final value has been written to the channel does not influence this method at all.
    ///
    /// ```
    /// use futures::join;
    /// use ufotofu::prelude::*;
    /// use ufotofu::channels::sssr::*;
    ///
    /// let (mut sender, mut receiver) = new_sssr(ufotofu::queues::new_static::<i16, 2>());
    ///
    /// pollster::block_on(async {
    ///     assert_eq!(sender.len(), 0);
    ///     assert!(sender.consume_item(300).await.is_ok());
    ///     assert_eq!(sender.len(), 1);
    ///     assert!(sender.consume_item(400).await.is_ok());
    ///     assert_eq!(sender.len(), 2);
    ///
    ///     assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
    ///     assert_eq!(sender.len(), 1);
    ///
    ///     assert!(sender.consume_final(-17).await.is_ok());
    ///     assert_eq!(sender.len(), 1);
    ///
    ///     assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
    ///     assert_eq!(sender.len(), 0);
    ///     assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
    ///     assert_eq!(sender.len(), 0);
    /// });
    /// ```
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the queue that buffers items for this channel is currently empty.
    ///
    /// Note that this method only considers regular items — whether the final value has been written to the channel does not influence this method at all.
    ///
    /// ```
    /// use futures::join;
    /// use ufotofu::prelude::*;
    /// use ufotofu::channels::sssr::*;
    ///
    /// let (mut sender, mut receiver) = new_sssr(ufotofu::queues::new_static::<i16, 2>());
    ///
    /// pollster::block_on(async {
    ///     assert!(sender.is_empty());
    ///     assert!(sender.consume_item(300).await.is_ok());
    ///     assert!(!sender.is_empty());
    ///     assert!(sender.consume_item(400).await.is_ok());
    ///     assert!(!sender.is_empty());
    ///
    ///     assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
    ///     assert!(!sender.is_empty());
    ///
    ///     assert!(sender.consume_final(-17).await.is_ok());
    ///     assert!(!sender.is_empty());
    ///
    ///     assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
    ///     assert!(sender.is_empty());
    ///     assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
    ///     assert!(sender.is_empty());
    /// });
    /// ```
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns whether the corresponding [`Receiver`] has been dropped already.
    ///
    /// ```
    /// use ufotofu::channels::sssr::*;
    ///
    /// let (sender, receiver) = new_sssr::<_, ()>(ufotofu::queues::new_static::<i16, 2>());
    ///
    /// assert!(!sender.is_receiver_dropped());
    /// core::mem::drop(receiver);
    /// assert!(sender.is_receiver_dropped());
    /// ```
    ///
    /// <br/>Counterpart: the [`Receiver::is_sender_dropped`] method.
    pub fn is_receiver_dropped(&self) -> bool {
        self.0.is_receiver_dropped()
    }
}

impl<Q: Queue, F> Consumer for Sender<Q, F> {
    type Item = Q::Item;
    type Final = F;
    type Error = Infallible;

    /// Writes the item into the buffer queue, waiting for buffer space to
    /// become available (by reading items from the corresponding [`Sender`]) if necessary.
    async fn consume(&mut self, val: Either<Self::Item, Self::Final>) -> Result<(), Self::Error> {
        self.0.consume(val).await
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        self.0.flush().await
    }
}

impl<Q: Queue, F> BulkConsumer for Sender<Q, F> {
    async fn expose_slots_gracefully<Fun, Ret>(&mut self, f: Fun) -> Result<Ret, (Fun, Self::Error)>
    where
        Fun: AsyncFnOnce(&mut [Self::Item]) -> (usize, Ret),
    {
        self.0.expose_slots_gracefully(f).await
    }
}

/// An endpoint for receiving items from an sssr channel.
///
/// Use the [`Producer`] or [`BulkProducer`] implementations to read data from the channel.
///
/// This type does *not* implement [`Clone`], making the channel a *single-receiver* channel.
///
/// <br/>Counterpart: the [`Sender`] type.
pub struct Receiver<Q, F>(AdvancedReceiver<Rc<State<Q, F>>, Q, F>);

impl<Q, F> fmt::Debug for Receiver<Q, F>
where
    Q: fmt::Debug,
    F: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<Q: Queue, F> Receiver<Q, F> {
    /// Returns the number of items in the queue that buffers items for this channel.
    ///
    /// Note that this method only considers regular items — whether the final value has been written to the channel does not influence this method at all.
    ///
    /// ```
    /// use futures::join;
    /// use ufotofu::prelude::*;
    /// use ufotofu::channels::sssr::*;
    ///
    /// let (mut sender, mut receiver) = new_sssr(ufotofu::queues::new_static::<i16, 2>());
    ///
    /// pollster::block_on(async {
    ///     assert_eq!(receiver.len(), 0);
    ///     assert!(sender.consume_item(300).await.is_ok());
    ///     assert_eq!(receiver.len(), 1);
    ///     assert!(sender.consume_item(400).await.is_ok());
    ///     assert_eq!(receiver.len(), 2);
    ///
    ///     assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
    ///     assert_eq!(receiver.len(), 1);
    ///
    ///     assert!(sender.consume_final(-17).await.is_ok());
    ///     assert_eq!(receiver.len(), 1);
    ///
    ///     assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
    ///     assert_eq!(receiver.len(), 0);
    ///     assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
    ///     assert_eq!(receiver.len(), 0);
    /// });
    /// ```
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the queue that buffers items for this channel is currently empty.
    ///
    /// Calling [`produce`](Producer::produce) on this receiver yields a *pending* future if and only if this returns `true`.
    ///
    /// Note that this method only considers regular items — whether the final value has been written to the channel does not influence this method at all.
    ///
    /// ```
    /// use futures::join;
    /// use ufotofu::prelude::*;
    /// use ufotofu::channels::sssr::*;
    ///
    /// let (mut sender, mut receiver) = new_sssr(ufotofu::queues::new_static::<i16, 2>());
    ///
    /// pollster::block_on(async {
    ///     assert!(receiver.is_empty());
    ///     assert!(sender.consume_item(300).await.is_ok());
    ///     assert!(!receiver.is_empty());
    ///     assert!(sender.consume_item(400).await.is_ok());
    ///     assert!(!receiver.is_empty());
    ///
    ///     assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
    ///     assert!(!receiver.is_empty());
    ///
    ///     assert!(sender.consume_final(-17).await.is_ok());
    ///     assert!(!receiver.is_empty());
    ///
    ///     assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
    ///     assert!(receiver.is_empty());
    ///     assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
    ///     assert!(receiver.is_empty());
    /// });
    /// ```
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns whether the corresponding [`Sender`] has been dropped already.
    ///
    /// ```
    /// use ufotofu::channels::sssr::*;
    ///
    /// let (sender, receiver) = new_sssr::<_, ()>(ufotofu::queues::new_static::<i16, 2>());
    ///
    /// assert!(!receiver.is_sender_dropped());
    /// core::mem::drop(sender);
    /// assert!(receiver.is_sender_dropped());
    /// ```
    ///
    /// <br/>Counterpart: the [`Sender::is_receiver_dropped`] method.
    pub fn is_sender_dropped(&self) -> bool {
        self.0.is_sender_dropped()
    }
}

impl<Q: Queue, F> Producer for Receiver<Q, F> {
    type Item = Q::Item;
    type Final = F;
    type Error = Infallible;

    /// Take an item from the buffer queue, waiting for an item to
    /// become available (by being consumed by the corresponding [`Sender`]) if necessary.
    async fn produce(&mut self) -> Result<Either<Self::Item, Self::Final>, Self::Error> {
        self.0.produce().await
    }

    async fn slurp(&mut self) -> Result<(), Self::Error> {
        self.0.slurp().await
    }
}

impl<Q: Queue, F> BulkProducer for Receiver<Q, F> {
    async fn expose_items_gracefully<Fun, Ret>(
        &mut self,
        f: Fun,
    ) -> Result<Either<Ret, (Fun, Self::Final)>, (Fun, Self::Error)>
    where
        Fun: AsyncFnOnce(&[Self::Item]) -> (usize, Ret),
    {
        self.0.expose_items_gracefully(f).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use futures::join;

    use crate::queues::new_static;

    #[test]
    fn test_spsc_sufficient_capacity() {
        let (mut sender, mut receiver) = new_sssr(new_static::<i16, 99>());

        pollster::block_on(async {
            assert!(sender.consume_item(300).await.is_ok());
            assert!(sender.consume_item(400).await.is_ok());
            assert!(sender.consume_item(500).await.is_ok());
            assert!(sender.consume_final(-17).await.is_ok());
            assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
            assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
            assert_eq!(500, receiver.produce().await.unwrap().unwrap_left());
            assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
        });
    }

    #[test]
    fn test_spsc_low_capacity() {
        pollster::block_on(async {
            let (mut sender, mut receiver) = new_sssr(new_static::<i16, 2>());

            let send_things = async {
                assert!(sender.consume_item(300).await.is_ok());
                assert!(sender.consume_item(400).await.is_ok());
                assert!(sender.consume_item(500).await.is_ok());
                assert!(sender.consume_final(-17).await.is_ok());
            };

            let receive_things = async {
                assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
                assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
                assert_eq!(500, receiver.produce().await.unwrap().unwrap_left());
                assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
            };

            join!(send_things, receive_things);
        });
    }

    #[test]
    fn test_spsc_immediate_final() {
        pollster::block_on(async {
            let (mut sender, mut receiver) = new_sssr(new_static::<i16, 3>());

            let send_things = async {
                assert!(sender.consume_final(-17).await.is_ok());
            };

            let receive_things = async {
                assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
            };

            join!(send_things, receive_things);
        });
    }

    #[test]
    fn test_spsc_receive_then_send_concurrently() {
        pollster::block_on(async {
            let (mut sender, mut receiver) = new_sssr(new_static::<i16, 2>());

            let send_things = async {
                assert!(sender.consume_item(300).await.is_ok());
                assert!(sender.consume_item(400).await.is_ok());
                assert!(sender.consume_item(500).await.is_ok());
                assert!(sender.consume_final(-17).await.is_ok());
            };

            let receive_things = async {
                assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
                assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
                assert_eq!(500, receiver.produce().await.unwrap().unwrap_left());
                assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
            };

            join!(receive_things, send_things);
        });
    }

    #[test]
    fn test_spsc_capacity_1() {
        pollster::block_on(async {
            let (mut sender, mut receiver) = new_sssr(new_static::<i16, 1>());

            let send_things = async {
                assert!(sender.consume_item(300).await.is_ok());
                assert!(sender.consume_item(400).await.is_ok());
                assert!(sender.consume_item(500).await.is_ok());
                assert!(sender.consume_final(-17).await.is_ok());
            };

            let receive_things = async {
                assert_eq!(300, receiver.produce().await.unwrap().unwrap_left());
                assert_eq!(400, receiver.produce().await.unwrap().unwrap_left());
                assert_eq!(500, receiver.produce().await.unwrap().unwrap_left());
                assert_eq!(-17, receiver.produce().await.unwrap().unwrap_right());
            };

            join!(receive_things, send_things);
        });
    }
}