use core::{
future::Future,
pin::Pin,
task::{Context, Poll, Waker},
};
use std::{
sync::{Arc, Mutex},
thread,
time::Duration,
};
use super::{AsyncLands, Commit, Unwritten, block_on};
#[derive(Debug, derive_more::Display)]
#[display("the table is gone")]
struct Gone;
impl core::error::Error for Gone {}
#[test]
fn all_names_every_position_without_holding_a_set() {
let commit = Commit::<Gone>::all();
assert!(commit.committed(0));
assert!(commit.committed(255));
assert!(commit.refusal().is_none());
}
#[test]
fn only_commits_what_it_names_and_holds_the_rest() {
let commit = Commit::only((0..250).chain([252]), Gone);
assert!(commit.committed(0));
assert!(commit.committed(249));
assert!(!commit.committed(250));
assert!(commit.committed(252));
assert_eq!(
commit.refusal().expect("a refusal").to_string(),
"the table is gone"
);
}
#[test]
fn none_holds_everything_and_still_says_why() {
let commit = Commit::none(Gone);
assert!(!commit.committed(0));
assert!(commit.into_refusal().is_some());
}
#[test]
fn the_unused_lane_takes_what_it_is_given() {
let mut lane = ();
let commit = block_on(AsyncLands::land(&mut lane, &[1u8, 2, 3]));
assert!(commit.committed(2));
assert!(commit.refusal().is_none());
}
#[test]
fn unwritten_carries_the_count_the_lane_could_not_and_keeps_the_refusal_walkable() {
let unwritten = Unwritten::new(256, 250, Gone);
assert_eq!(unwritten.staged(), 256);
assert_eq!(unwritten.committed(), 250);
assert_eq!(
unwritten.to_string(),
"the write lane committed 250 of 256: the table is gone"
);
let source = core::error::Error::source(&unwritten).expect("the lane's own refusal");
assert_eq!(source.to_string(), "the table is gone");
}
#[derive(Debug, Default)]
struct Landing {
done: bool,
waker: Option<Waker>,
}
#[derive(Debug, Clone, Default)]
struct Later(Arc<Mutex<Landing>>);
impl Later {
fn land(&self) {
let waker = {
let mut landing = self.0.lock().expect("the landing");
landing.done = true;
landing.waker.take()
};
if let Some(waker) = waker {
waker.wake();
}
}
}
impl Future for Later {
type Output = u8;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u8> {
let mut landing = self.0.lock().expect("the landing");
if landing.done {
return Poll::Ready(7);
}
landing.waker = Some(cx.waker().clone());
Poll::Pending
}
}
#[test]
fn the_thread_driver_parks_until_another_thread_wakes_it() {
let later = Later::default();
let landing = later.clone();
let writer = thread::spawn(move || {
thread::sleep(Duration::from_millis(20));
landing.land();
});
assert_eq!(block_on(later), 7);
writer.join().expect("the writing thread");
}