use core::{pin::pin, time::Duration};
use std::{
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
thread,
};
use super::{Arm, Taken, arm, bounded, park_on, select};
#[derive(Debug, PartialEq, Eq)]
enum Which {
Left(u8),
Right(u8),
}
#[test]
fn a_thread_producer_reaches_a_thread_consumer() {
let (tx, rx) = bounded::<u8>(2);
let producer = thread::spawn(move || {
tx.send(1).expect("the consumer is here");
tx.send(2).expect("the consumer is here");
});
assert_eq!(rx.recv(), Some(1));
assert_eq!(rx.recv(), Some(2));
producer.join().expect("the producer thread");
assert_eq!(rx.recv(), None, "every sender is gone");
}
#[tokio::test]
async fn a_thread_producer_reaches_a_task_consumer() {
let (tx, rx) = bounded::<u8>(2);
let producer = thread::spawn(move || {
tx.send(1).expect("the consumer is here");
tx.send(2).expect("the consumer is here");
});
assert_eq!(rx.recv_async().await, Some(1));
assert_eq!(rx.recv_async().await, Some(2));
producer.join().expect("the producer thread");
assert_eq!(rx.recv_async().await, None);
}
#[tokio::test]
async fn a_task_producer_reaches_a_thread_consumer() {
let (tx, rx) = bounded::<u8>(2);
let consumer = thread::spawn(move || {
let mut taken = Vec::new();
while let Some(item) = rx.recv() {
taken.push(item);
}
taken
});
tx.send_async(1).await.expect("the consumer is here");
tx.send_async(2).await.expect("the consumer is here");
drop(tx);
assert_eq!(consumer.join().expect("the consumer thread"), [1, 2]);
}
#[tokio::test]
async fn a_task_producer_reaches_a_task_consumer() {
let (tx, rx) = bounded::<u8>(2);
let producer = tokio::spawn(async move {
tx.send_async(1).await.expect("the consumer is here");
tx.send_async(2).await.expect("the consumer is here");
});
assert_eq!(rx.recv_async().await, Some(1));
assert_eq!(rx.recv_async().await, Some(2));
producer.await.expect("the producer task");
assert_eq!(rx.recv_async().await, None);
}
#[test]
fn the_capacity_is_a_number_because_there_is_no_unbounded_door() {
let (tx, rx) = bounded::<u8>(3);
assert_eq!(tx.capacity(), 3);
assert_eq!(rx.capacity(), 3);
assert!(tx.is_empty());
tx.send(1).expect("room");
assert_eq!(tx.len(), 1);
assert_eq!(rx.len(), 1);
}
#[test]
fn a_full_conduit_blocks_the_thread_until_a_receive_makes_room() {
let (tx, rx) = bounded::<u8>(1);
tx.send(1).expect("room for one");
let sent = Arc::new(AtomicUsize::new(0));
let producer = {
let tx = tx.clone();
let sent = sent.clone();
thread::spawn(move || {
for item in 2..=4 {
tx.send(item).expect("the consumer is here");
sent.fetch_add(1, Ordering::SeqCst);
}
})
};
thread::sleep(Duration::from_millis(50));
assert_eq!(
sent.load(Ordering::SeqCst),
0,
"nothing gets through while the one slot is occupied"
);
let mut taken = Vec::new();
while taken.len() < 4 {
taken.push(rx.recv().expect("the producer is still alive"));
}
producer.join().expect("the producer thread");
assert_eq!(taken, [1, 2, 3, 4], "every item arrived; none was dropped");
}
#[tokio::test]
async fn a_full_conduit_parks_the_task_until_a_receive_makes_room() {
let (tx, rx) = bounded::<u8>(1);
tx.send_async(1).await.expect("room for one");
let producer = {
let tx = tx.clone();
tokio::spawn(async move {
tx.send_async(2).await.expect("eventually room");
})
};
assert_eq!(rx.recv_async().await, Some(1));
producer.await.expect("the producer task");
assert_eq!(rx.recv_async().await, Some(2));
}
#[test]
fn a_zero_capacity_conduit_is_a_rendezvous_rather_than_a_refusal() {
let (tx, rx) = bounded::<u8>(0);
assert_eq!(tx.capacity(), 0);
assert_eq!(
tx.try_send(1).expect_err("nowhere to park it").into_inner(),
1,
"an impatient door finds a rendezvous permanently full"
);
let producer = thread::spawn(move || tx.send(7).expect("the consumer is here"));
assert_eq!(rx.recv(), Some(7));
producer.join().expect("the producer thread");
}
#[test]
fn try_send_refuses_a_full_conduit_and_a_gone_one_alike_and_the_predicate_tells_them_apart() {
let (tx, rx) = bounded::<u8>(1);
tx.try_send(1).expect("room for one");
let full = tx.try_send(2).expect_err("the one slot is occupied");
assert_eq!(full.into_inner(), 2, "the item comes back");
assert!(
!tx.is_disconnected(),
"full, not gone — and this is what says which"
);
drop(rx);
let gone = tx.try_send(3).expect_err("the consumer has hung up");
assert!(tx.is_disconnected());
assert_eq!(
gone.to_string(),
"the item was not taken — the conduit is full, or every receiver has hung up",
"ONE sentence for the two failures, because the predicate above is what says which"
);
assert_eq!(gone.into_inner(), 3);
}
#[test]
fn try_recv_answers_empty_then_the_item_then_hung_up() {
let (tx, rx) = bounded::<u8>(2);
assert_eq!(rx.try_recv(), Taken::Empty, "nothing is queued yet");
tx.send(5).expect("room");
assert_eq!(rx.try_recv(), Taken::Item(5));
assert!(rx.try_recv().is_empty());
tx.send(6).expect("room");
drop(tx);
assert_eq!(
rx.try_recv(),
Taken::Item(6),
"a disconnected conduit answers what is still queued"
);
assert_eq!(rx.try_recv(), Taken::HungUp);
assert!(rx.is_disconnected());
}
#[test]
fn recv_timeout_reads_its_own_expiry_as_empty_and_the_end_as_hung_up() {
let (tx, rx) = bounded::<u8>(2);
assert_eq!(
rx.recv_timeout(Duration::from_millis(20)),
Taken::Empty,
"the expiry says nothing about the channel"
);
tx.send(8).expect("room");
assert_eq!(
rx.recv_timeout(Duration::from_secs(2)).into_item(),
Some(8),
"an item ends the wait early"
);
drop(tx);
assert_eq!(rx.recv_timeout(Duration::from_secs(2)), Taken::HungUp);
}
#[test]
fn a_drain_takes_the_whole_burst_without_waiting() {
let (tx, rx) = bounded::<u8>(4);
for item in 1..=3 {
tx.send(item).expect("room");
}
assert_eq!(rx.drain().collect::<Vec<_>>(), [1, 2, 3]);
assert!(rx.is_empty());
}
#[test]
fn a_second_receiver_is_another_consumer_rather_than_another_copy() {
let (tx, first) = bounded::<u8>(4);
let second = first.clone();
tx.send(1).expect("room");
tx.send(2).expect("room");
let mut taken = [
first.recv().expect("an item"),
second.recv().expect("an item"),
];
taken.sort_unstable();
assert_eq!(taken, [1, 2], "each item reached exactly one of them");
}
#[test]
fn the_sync_select_serves_both_arms_under_the_turn_cursor() {
let (left_in, left) = bounded::<u8>(2);
let (right_in, right) = bounded::<u8>(2);
left_in.send(1).expect("room");
right_in.send(2).expect("room");
let first = {
let mut a = pin!(arm(true, &left, Which::Left));
let mut b = pin!(arm(true, &right, Which::Right));
let mut arms: [Arm<'_, Option<Which>>; 2] = [a.as_mut(), b.as_mut()];
park_on(select(0, &mut arms), Duration::from_secs(2))
};
assert_eq!(first, Some(Some((0, Some(Which::Left(1))))));
left_in.send(3).expect("room");
let second = {
let mut a = pin!(arm(true, &left, Which::Left));
let mut b = pin!(arm(true, &right, Which::Right));
let mut arms: [Arm<'_, Option<Which>>; 2] = [a.as_mut(), b.as_mut()];
park_on(select(1, &mut arms), Duration::from_secs(2))
};
assert_eq!(second, Some(Some((1, Some(Which::Right(2))))));
}
#[tokio::test]
async fn the_async_select_serves_both_arms_under_the_turn_cursor() {
let (left_in, left) = bounded::<u8>(2);
let (right_in, right) = bounded::<u8>(2);
left_in.send_async(1).await.expect("room");
right_in.send_async(2).await.expect("room");
let first = {
let mut a = pin!(arm(true, &left, Which::Left));
let mut b = pin!(arm(true, &right, Which::Right));
let mut arms: [Arm<'_, Option<Which>>; 2] = [a.as_mut(), b.as_mut()];
select(0, &mut arms).await
};
assert_eq!(first, Some((0, Some(Which::Left(1)))));
left_in.send_async(3).await.expect("room");
let second = {
let mut a = pin!(arm(true, &left, Which::Left));
let mut b = pin!(arm(true, &right, Which::Right));
let mut arms: [Arm<'_, Option<Which>>; 2] = [a.as_mut(), b.as_mut()];
select(1, &mut arms).await
};
assert_eq!(second, Some((1, Some(Which::Right(2)))));
}
#[test]
fn a_hung_up_arm_says_so_once_and_then_retires_from_the_rotation() {
let (dead_in, dead) = bounded::<u8>(1);
let (live_in, live) = bounded::<u8>(1);
drop(dead_in);
let told = {
let mut a = pin!(arm(true, &dead, Which::Left));
let mut b = pin!(arm(true, &live, Which::Right));
let mut arms: [Arm<'_, Option<Which>>; 2] = [a.as_mut(), b.as_mut()];
park_on(select(0, &mut arms), Duration::from_secs(2))
};
assert_eq!(told, Some(Some((0, None))));
live_in.send(9).expect("room");
let served = {
let mut a = pin!(arm(false, &dead, Which::Left));
let mut b = pin!(arm(true, &live, Which::Right));
let mut arms: [Arm<'_, Option<Which>>; 2] = [a.as_mut(), b.as_mut()];
park_on(select(0, &mut arms), Duration::from_secs(2))
};
assert_eq!(served, Some(Some((1, Some(Which::Right(9))))));
}
#[test]
fn a_select_over_only_retired_arms_waits_out_its_sweep() {
let (dead_in, dead) = bounded::<u8>(1);
drop(dead_in);
let mut a = pin!(arm(false, &dead, Which::Left));
let mut arms: [Arm<'_, Option<Which>>; 1] = [a.as_mut()];
assert!(
park_on(select(0, &mut arms), Duration::from_millis(30)).is_none(),
"the deadline expires, which is what a park with nothing to hear does"
);
}
#[test]
fn a_select_over_nothing_is_the_honest_no_channel_left() {
let mut arms: [Arm<'_, u8>; 0] = [];
assert_eq!(
park_on(select(0, &mut arms), Duration::from_millis(50)),
Some(None)
);
}
#[test]
fn a_timed_out_park_leaves_the_message_where_the_next_one_finds_it() {
let (tx, rx) = bounded::<u8>(4);
assert!(park_on(rx.recv_async(), Duration::from_millis(30)).is_none());
tx.send(4).expect("room");
assert_eq!(
park_on(rx.recv_async(), Duration::from_secs(2)),
Some(Some(4))
);
}
#[test]
fn a_probe_answers_what_is_queued_and_takes_none_of_it() {
let (tx, rx) = bounded::<u8>(4);
tx.send(1).expect("room");
tx.send(2).expect("room");
assert!(rx.readable(), "two items are queued");
assert_eq!(rx.len(), 2, "the probe took one of them");
assert!(rx.readable());
assert_eq!(rx.try_recv(), Taken::Item(1));
assert_eq!(rx.try_recv(), Taken::Item(2));
}
#[test]
fn a_probe_over_a_line_nobody_speaks_on_parks_rather_than_answering() {
let (tx, rx) = bounded::<u8>(4);
assert!(
park_on(rx.readable_async(), Duration::from_millis(50)).is_none(),
"the probe answered on a line nothing had reached"
);
drop(tx);
}
#[test]
fn a_probe_wakes_on_an_item_and_on_the_last_sender_going() {
let (tx, rx) = bounded::<u8>(4);
let speaker = thread::spawn(move || {
thread::sleep(Duration::from_millis(20));
tx.send(7).expect("the consumer is here");
thread::sleep(Duration::from_millis(20));
});
assert_eq!(
park_on(rx.readable_async(), Duration::from_secs(5)),
Some(true),
"the probe slept through an item landing"
);
assert_eq!(rx.try_recv(), Taken::Item(7));
assert_eq!(
park_on(rx.readable_async(), Duration::from_secs(5)),
Some(false),
"the probe slept through the last sender going"
);
speaker.join().expect("the speaker thread");
}
#[test]
fn what_is_queued_outlives_the_end_and_the_probe_says_so() {
let (tx, rx) = bounded::<u8>(4);
tx.send(9).expect("room");
drop(tx);
assert!(
rx.readable(),
"an item outlives the sender that put it there"
);
assert_eq!(rx.try_recv(), Taken::Item(9));
assert!(!rx.readable(), "and now there is nothing and nobody");
}
#[test]
fn a_probe_never_becomes_the_second_reader_a_handoff_could_jump() {
let (tx, rx) = bounded::<u8>(8);
let mut watching = pin!(rx.readable_async());
assert!(park_on(watching.as_mut(), Duration::from_millis(20)).is_none());
let speaker = thread::spawn(move || {
for step in 0..6u8 {
tx.send(step).expect("the consumer is here");
}
});
speaker.join().expect("the speaker thread");
let mut took = Vec::new();
while let Taken::Item(item) = rx.try_recv() {
took.push(item);
}
assert_eq!(took, [0, 1, 2, 3, 4, 5], "the queue is the only order");
assert_eq!(
park_on(watching.as_mut(), Duration::from_secs(5)),
Some(false)
);
}
#[test]
fn a_probe_that_expires_gives_its_seat_back() {
let (tx, rx) = bounded::<u8>(4);
for _ in 0..200 {
assert!(park_on(rx.readable_async(), Duration::from_millis(1)).is_none());
}
assert_eq!(rx.parked(), 0, "an expired probe left its waker behind");
{
let mut watching = pin!(rx.readable_async());
for _ in 0..20 {
assert!(park_on(watching.as_mut(), Duration::from_millis(1)).is_none());
}
assert_eq!(rx.parked(), 1, "one probe took more than one seat");
}
assert_eq!(rx.parked(), 0, "a dropped probe left its waker behind");
drop(tx);
}
#[test]
fn a_probe_never_answers_ended_over_a_queue_that_still_holds_something() {
let stop = Arc::new(AtomicBool::new(false));
let burners: Vec<_> = (0..8)
.map(|_| {
let stop = Arc::clone(&stop);
thread::spawn(move || {
let mut spun = 0u64;
while !stop.load(Ordering::Relaxed) {
spun = spun.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
core::hint::black_box(spun);
}
})
})
.collect();
let mut lost = 0usize;
let mut first = 0usize;
for round in 0..3_000 {
let (tx, rx) = bounded::<u8>(4);
let gate = Arc::new(std::sync::Barrier::new(5));
let senders: Vec<_> = (0..4u8)
.map(|which| {
let tx = tx.clone();
let gate = Arc::clone(&gate);
thread::spawn(move || {
gate.wait();
tx.send(which).expect("the receiver is alive");
})
})
.collect();
drop(tx);
gate.wait();
let mut taken = 0usize;
loop {
while let Taken::Item(_) = rx.try_recv() {
taken += 1;
}
if !rx.readable() {
break;
}
}
for sender in senders {
sender.join().expect("the sender ends");
}
if taken != 4 {
if lost == 0 {
first = round;
}
lost += 1;
}
}
stop.store(true, Ordering::Relaxed);
for burner in burners {
burner.join().expect("the burner ends");
}
assert_eq!(
lost, 0,
"the drain stopped {lost} times on a probe that answered `ended` over a queue that still held \
an item — first at round {first}. The item is lost, and nothing reports it"
);
}