Skip to content

Commit

Permalink
fix: add test for Send and fix clone stack overflow
Browse files Browse the repository at this point in the history
  • Loading branch information
hansl committed Apr 5, 2021
1 parent 45e4619 commit e4cf281
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
13 changes: 8 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ where
/// Finally, a Box of Waiter implements clone by calling the WaiterClone::clone_box method.
impl Clone for Box<dyn Waiter> {
fn clone(&self) -> Self {
self.clone_box()
WaiterClone::clone_box(self.as_ref())
}
}

Expand Down Expand Up @@ -118,12 +118,15 @@ impl Waiter for Box<dyn Waiter> {
/// Then when you're ready to start a process that needs to wait, use the [start()]
/// function. Every wait period, call the [wait()] function on it (it may block the
/// thread).
#[derive(Clone)]
pub struct Delay {
inner: Box<dyn Waiter>,
}

impl Delay {
pub fn from(inner: Box<dyn Waiter>) -> Self {
Delay { inner }
}

/// A Delay that never waits. This can hog resources, so careful.
pub fn instant() -> Self {
Self::from(Box::new(InstantWaiter {}))
Expand Down Expand Up @@ -177,9 +180,9 @@ impl Delay {
}
}

impl<T: Waiter + 'static> From<Box<T>> for Delay {
fn from(inner: Box<T>) -> Self {
Delay { inner }
impl Clone for Delay {
fn clone(&self) -> Self {
Self::from(self.inner.clone_box())
}
}

Expand Down
27 changes: 25 additions & 2 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ fn counter_works() {
#[test]
fn clone_works() {
let mut waiter1 = Delay::count_timeout(3);
eprintln!("1");
let mut waiter2 = waiter1.clone();
eprintln!("2");

waiter1.start();
assert!(waiter1.wait().is_ok());
Expand Down Expand Up @@ -92,3 +90,28 @@ fn restart_works() {
std::thread::sleep(Duration::from_millis(50));
assert!(waiter.wait().is_err());
}

#[test]
fn can_send_between_threads() {
let mut waiter = Delay::count_timeout(5);
let (tx, rx) = std::sync::mpsc::channel();
let (tx_end, rx_end) = std::sync::mpsc::channel();

std::thread::spawn(move || {
waiter.start();

while let Some(x) = rx.recv().unwrap_or(None) {
for _i in 1..x {
waiter.wait().unwrap();
}
}

tx_end.send(()).unwrap();
});

tx.send(Some(4)).unwrap();
tx.send(Some(1)).unwrap();
tx.send(None).unwrap();

rx_end.recv_timeout(Duration::from_millis(100)).unwrap();
}

0 comments on commit e4cf281

Please sign in to comment.