ufotofu 0.12.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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! A **S**ingle-**S**ender **S**ingle-**R**eceiver FIFO channel.
//!
//! The entrypoint to this module is the [`new_sssr`] function. You call it with a reference to a [`State`], 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 buffer 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
//!
//! An example with a stack-allocated [`State`]:
//!
//! ```
//! use futures::join;
//! use ufotofu::prelude::*;
//! use ufotofu::channels::advanced::sssr::*;
//!
//! // Allocate a new opaque state on the stack.
//! let state = State::new(ufotofu::queues::new_static::<i16, 2>());
//!
//! // Create a channel whose endpoints reference the shared state through vanilla reference.
//! // The state must outlive the endpoints, otherwise you would get a compiler error.
//! let (mut sender, mut receiver) = new_sssr(&state);
//!
//! 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::{
    cell::Cell,
    convert::Infallible,
    fmt,
    ops::{Deref, DerefMut},
};

use either::Either::{self, *};

use fairly_unsafe_cell::*;
use frugal_async::{Mutex, TakeCell};

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

/// The state shared between the senders and receivers of an sssr in-memory channel.
///
/// This type is fully opaque, we expose it merely to give control over where it is allocated.
///
/// `Q` is the type of the internal item queue, `F` is the type of final items for the channel.
pub struct State<Q, F> {
    // We need a Mutex here because `expose_slots` and `expose_items` can be called concurrently on the two endpoints.
    queue: Mutex<Q>,
    // Safety: We never return refs to this from any method, and we never hold a borrow across `.await` points.
    // Hence, no concurrent refs can exist.
    buffered_final_value: FairlyUnsafeCell<Option<F>>,
    // We track the number of items in the queue here, so that we can access it without waiting for the Mutex of the queue itself.
    // A bit awkward, but this enables sync access to the current count.
    len: Cell<usize>,
    // Empty while the sender cannot make progress.
    notify_the_sender: TakeCell<()>,
    // Empty while the receiver cannot make progress.
    notify_the_receiver: TakeCell<()>,
    // True iff neither endpoint has been dropped yet.
    did_any_endpoint_drop_yet: Cell<bool>,
}

impl<Q, F> fmt::Debug for State<Q, F>
where
    Q: fmt::Debug,
    F: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("State")
            .field("queue_item_count", &self.len)
            .field("queue", &self.queue)
            .field("buffered_final_value", &self.buffered_final_value)
            .finish()
    }
}

impl<Q: Queue, F> State<Q, F> {
    /// Creates a new [`State`], using the given queue as backing storage for the channel.
    pub fn new(queue: Q) -> Self {
        State {
            len: Cell::new(queue.len()),
            queue: Mutex::new(queue),
            buffered_final_value: FairlyUnsafeCell::new(None),
            notify_the_sender: TakeCell::new_with(()),
            notify_the_receiver: TakeCell::new(),
            did_any_endpoint_drop_yet: Cell::new(false),
        }
    }

    /// Returns the number of items in the queue that buffers items for this channel.
    fn len(&self) -> usize {
        self.len.get()
    }

    /// Returns whether the queue that buffers items for this channel is currently empty.
    fn is_empty(&self) -> bool {
        self.len.get() == 0
    }

    /// Performs the actual sequence-related logic of closing the channel.
    fn close(&self, fin: F) {
        // Store the final value for later access by the Senders.
        let mut last = unsafe { self.buffered_final_value.borrow_mut() };
        *last = Some(fin);

        self.notify_the_receiver.set(());
    }
}

/// Creates a new single-sender single-receiver channel in the form of a [`Sender`] and a [`Receiver`] endpoint, which communicate via the given [`State`].
///
/// See [`ufotofu::channels::new_sssr`](crate::channels::new_sssr) for an API that hides the explicit [`State`] management (by transparently allocating the state on the heap and freeing it automatically after both endpoints are dropped).
///
/// #### Example
///
/// An example with a stack-allocated [`State`]:
///
/// ```
/// use futures::join;
/// use ufotofu::prelude::*;
/// use ufotofu::channels::advanced::sssr::*;
///
/// // Allocate a new opaque state on the stack.
/// let state = State::new(ufotofu::queues::new_static::<i16, 2>());
///
/// // Create a channel whose endpoints reference the shared state through vanilla reference.
/// // The state must outlive the endpoints, otherwise you would get a compiler error.
/// let (mut sender, mut receiver) = new_sssr(&state);
///
/// 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<R, Q, F>(state_ref: R) -> (Sender<R, Q, F>, Receiver<R, Q, F>)
where
    R: Deref<Target = State<Q, F>> + Clone,
{
    (
        Sender {
            state: state_ref.clone(),
        },
        Receiver { state: state_ref },
    )
}

/// 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.
#[derive(Debug)]
pub struct Sender<R, Q, F>
where
    R: Deref<Target = State<Q, F>>,
{
    state: R,
}

impl<R, Q, F> Drop for Sender<R, Q, F>
where
    R: Deref<Target = State<Q, F>>,
{
    fn drop(&mut self) {
        self.state.did_any_endpoint_drop_yet.set(true)
    }
}

impl<R, Q, F> Sender<R, Q, F>
where
    R: Deref<Target = State<Q, F>>,
    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::advanced::sssr::*;
    ///
    /// let state = State::new(ufotofu::queues::new_static::<i16, 2>());
    /// let (mut sender, mut receiver) = new_sssr(&state);
    ///
    /// 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.state.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::advanced::sssr::*;
    ///
    /// let state = State::new(ufotofu::queues::new_static::<i16, 2>());
    /// let (mut sender, mut receiver) = new_sssr(&state);
    ///
    /// 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.state.is_empty()
    }

    /// Returns whether the corresponding [`Receiver`] has been dropped already.
    ///
    /// ```
    /// use ufotofu::channels::advanced::sssr::*;
    ///
    /// let state: State<_, ()> = State::new(ufotofu::queues::new_static::<i16, 2>());
    /// let (sender, receiver) = new_sssr(&state);
    ///
    /// 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.state.did_any_endpoint_drop_yet.get()
    }
}

impl<R: Deref<Target = State<Q, F>>, Q: Queue, F> Consumer for Sender<R, 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> {
        match val {
            Left(mut item) => {
                loop {
                    // Try to buffer the item.
                    let did_it_work = {
                        // Inside a block to drop the Mutex access before awaiting on the notifier.
                        self.state.queue.write().await.deref_mut().enqueue(item)
                    };

                    match did_it_work {
                        // Enqueueing failed.
                        Some(item_) => {
                            // Wait for queue space.
                            let () = self.state.notify_the_sender.take().await;
                            // Go into the next iteration of the loop, where enqueeuing is guaranteed to succeed.
                            item = item_;
                        }
                        // Enqueueing succeeded.
                        None => {
                            self.state.len.set(self.state.len.get() + 1);
                            self.state.notify_the_receiver.set(());
                            return Ok(());
                        }
                    }
                }
            }

            Right(fin) => {
                self.state.close(fin);
                Ok(())
            }
        }
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(()) // Nothing to do.
    }
}

impl<R: Deref<Target = State<Q, F>>, Q: Queue, F> BulkConsumer for Sender<R, 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),
    {
        let mut f = Some(f);

        loop {
            let ret = self
                .state
                .queue
                .write()
                .await
                .deref_mut()
                .expose_slots(async |queue_slots| {
                    if queue_slots.is_empty() {
                        (0, None)
                    } else {
                        let (amount, ret) = (f.take().expect(
                            "Running this branch only once, we return after having called f",
                        ))(queue_slots)
                        .await;
                        self.state.len.set(self.state.len.get() + amount);
                        self.state.notify_the_receiver.set(());
                        (amount, Some(ret))
                    }
                })
                .await;

            match ret {
                None => {
                    let () = self.state.notify_the_sender.take().await;
                    // And now go into the next iteration of the loop, where there will be slots available.
                }
                Some(ret) => return Ok(ret),
            }
        }
    }
}

/// 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.
#[derive(Debug)]
pub struct Receiver<R, Q, F>
where
    R: Deref<Target = State<Q, F>>,
{
    state: R,
}

impl<R, Q, F> Drop for Receiver<R, Q, F>
where
    R: Deref<Target = State<Q, F>>,
{
    fn drop(&mut self) {
        self.state.did_any_endpoint_drop_yet.set(true)
    }
}

impl<R: Deref<Target = State<Q, F>>, Q: Queue, F> Receiver<R, 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::advanced::sssr::*;
    ///
    /// let state = State::new(ufotofu::queues::new_static::<i16, 2>());
    /// let (mut sender, mut receiver) = new_sssr(&state);
    ///
    /// 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.state.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::advanced::sssr::*;
    ///
    /// let state = State::new(ufotofu::queues::new_static::<i16, 2>());
    /// let (mut sender, mut receiver) = new_sssr(&state);
    ///
    /// 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.state.is_empty()
    }

    /// Returns whether the corresponding [`Sender`] has been dropped already.
    ///
    /// ```
    /// use ufotofu::channels::advanced::sssr::*;
    ///
    /// let state: State<_, ()> = State::new(ufotofu::queues::new_static::<i16, 2>());
    /// let (sender, receiver) = new_sssr(&state);
    ///
    /// 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.state.did_any_endpoint_drop_yet.get()
    }
}

impl<R: Deref<Target = State<Q, F>>, Q: Queue, F> Producer for Receiver<R, 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> {
        loop {
            // Try to obtain the next item.
            match self.state.queue.write().await.deref_mut().dequeue() {
                // At least one item was in the buffer, return it.
                Some(item) => {
                    self.state.len.set(self.state.len.get() - 1);
                    self.state.notify_the_sender.set(());
                    return Ok(Left(item));
                }
                None => {
                    // Buffer is empty.
                    // But perhaps the final item has been consumed already, or an error was requested?
                    match unsafe { self.state.buffered_final_value.borrow_mut().take() } {
                        Some(fin) => {
                            return Ok(Right(fin));
                        }
                        None => {
                            // No last item yet, so we wait until something changes.
                            // But we do the waiting outside this `match` block, so that the mutex is released first.
                        }
                    }
                }
            }

            // No last item yet, so we wait until something changes.
            let () = self.state.notify_the_receiver.take().await;
            // Go into the next iteration of the loop, where progress will be made.
        }
    }

    async fn slurp(&mut self) -> Result<(), Self::Error> {
        Ok(()) // Nothing to do.
    }
}

impl<R: Deref<Target = State<Q, F>>, Q: Queue, F> BulkProducer for Receiver<R, 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),
    {
        let mut f = Some(f);

        loop {
            let ret = self
                .state
                .queue
                .write()
                .await
                .expose_items(async |queue_items| {
                    if queue_items.is_empty() {
                        match unsafe { self.state.buffered_final_value.borrow_mut().take() } {
                            Some(fin) => (0, Some(Right(fin))),
                            None => (0, None),
                        }
                    } else {
                        let (amount, ret) = (f.take().expect(
                            "Running this branch only once, we return after having called f",
                        ))(queue_items)
                        .await;
                        self.state.len.set(self.state.len.get() - amount);
                        self.state.notify_the_sender.set(());
                        (amount, Some(Left(ret)))
                    }
                })
                .await;

            match ret {
                None => {
                    let () = self.state.notify_the_receiver.take().await;
                    // And now go into the next iteration of the loop, where there will be slots available.
                }
                Some(Left(ret)) => return Ok(Left(ret)),
                Some(Right(fin)) => {
                    return Ok(Right((
                        f.take()
                            .expect("Branch guarded by early return of Ok(Left(_))"),
                        fin,
                    )))
                }
            }
        }
    }
}

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

    use futures::join;

    use crate::queues::new_static;

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

        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 state = State::new(new_static::<i16, 2>());
            let (mut sender, mut receiver) = new_sssr(&state);

            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 state = State::new(new_static::<i16, 3>());
            let (mut sender, mut receiver) = new_sssr(&state);

            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 state = State::new(new_static::<i16, 2>());
            let (mut sender, mut receiver) = new_sssr(&state);

            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 state = State::new(new_static::<i16, 1>());
            let (mut sender, mut receiver) = new_sssr(&state);

            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);
        });
    }
}