use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
type Slot<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub(crate) struct Slots<'a, T> {
slots: Vec<Slot<'a, T>>,
limit: usize,
}
impl<'a, T> Slots<'a, T> {
pub(crate) fn new(limit: usize) -> Slots<'a, T> {
let limit = limit.max(1);
Slots {
slots: Vec::new(),
limit,
}
}
pub(crate) fn has_room(&self) -> bool {
self.slots.len() < self.limit
}
pub(crate) fn push(&mut self, future: impl Future<Output = T> + Send + 'a) {
self.slots.push(Box::pin(future));
}
#[cfg(test)]
fn len(&self) -> usize {
self.slots.len()
}
pub(crate) async fn next_ready(&mut self) -> Option<T> {
if self.slots.is_empty() {
return None;
}
let (index, output) = PollAll(&mut self.slots).await;
drop(self.slots.swap_remove(index));
Some(output)
}
}
struct PollAll<'s, 'a, T>(&'s mut Vec<Slot<'a, T>>);
impl<T> Future for PollAll<'_, '_, T> {
type Output = (usize, T);
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<(usize, T)> {
for (index, slot) in self.get_mut().0.iter_mut().enumerate() {
if let Poll::Ready(output) = slot.as_mut().poll(cx) {
return Poll::Ready((index, output));
}
}
Poll::Pending
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures_lite::future::poll_once;
use ostrya_rt::block_on;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
struct Gated {
gate: Arc<AtomicUsize>,
release: usize,
value: usize,
}
impl Future for Gated {
type Output = usize;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<usize> {
if self.gate.load(Ordering::SeqCst) >= self.release {
return Poll::Ready(self.value);
}
cx.waker().wake_by_ref();
Poll::Pending
}
}
#[test]
fn slots_refill_from_the_plan_up_to_the_limit() {
block_on(async {
let mut work: Vec<usize> = (0..7).collect();
work.reverse();
let mut slots = Slots::new(3);
let mut done = Vec::new();
let mut high_water = 0;
loop {
while slots.has_room()
&& let Some(item) = work.pop()
{
slots.push(async move { item });
}
high_water = high_water.max(slots.len());
let Some(output) = slots.next_ready().await else {
break;
};
done.push(output);
}
done.sort_unstable();
assert_eq!(done, (0..7).collect::<Vec<_>>());
assert_eq!(high_water, 3);
});
}
#[test]
fn the_first_ready_slot_is_the_one_returned() {
block_on(async {
let gate = Arc::new(AtomicUsize::new(0));
let mut slots = Slots::new(4);
for (value, release) in [(10usize, 3usize), (11, 1), (12, 2)] {
slots.push(Gated {
gate: gate.clone(),
release,
value,
});
}
gate.store(1, Ordering::SeqCst);
assert_eq!(slots.next_ready().await, Some(11));
gate.store(2, Ordering::SeqCst);
assert_eq!(slots.next_ready().await, Some(12));
gate.store(3, Ordering::SeqCst);
assert_eq!(slots.next_ready().await, Some(10));
assert_eq!(slots.next_ready().await, None);
});
}
#[test]
fn an_error_drops_every_slot_still_in_flight() {
block_on(async {
struct Tracked<'a> {
dropped: &'a AtomicUsize,
}
impl Future for Tracked<'_> {
type Output = Result<(), &'static str>;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Pending
}
}
impl Drop for Tracked<'_> {
fn drop(&mut self) {
self.dropped.fetch_add(1, Ordering::SeqCst);
}
}
let dropped = AtomicUsize::new(0);
let outcome = {
let mut slots = Slots::new(4);
for _ in 0..3 {
slots.push(Tracked { dropped: &dropped });
}
slots.push(async { Err("object not found") });
let outcome = slots.next_ready().await;
assert_eq!(dropped.load(Ordering::SeqCst), 0);
assert_eq!(slots.len(), 3);
outcome
};
assert_eq!(outcome, Some(Err("object not found")));
assert_eq!(dropped.load(Ordering::SeqCst), 3);
});
}
#[test]
fn an_empty_set_is_ready_immediately() {
block_on(async {
let mut slots: Slots<'_, usize> = Slots::new(2);
assert_eq!(poll_once(slots.next_ready()).await, Some(None));
assert!(slots.has_room());
});
}
#[test]
fn the_largest_limit_makes_a_set() {
block_on(async {
let mut slots = Slots::new(usize::MAX);
slots.push(async { 1usize });
assert!(slots.has_room());
assert_eq!(slots.next_ready().await, Some(1));
});
}
}