vthread 0.1.0

Bounded carrier-affine virtual threads for Rust
Documentation
use crate::{Runtime, local_scope};

#[test]
fn dropping_a_local_join_handle_keeps_the_child_owned_by_its_scope() {
    let runtime = Runtime::new().unwrap();
    runtime
        .run_scope(|scope| {
            scope
                .spawn("parent", || {
                    let mut value = 0;
                    local_scope(|local| {
                        std::mem::forget(local.spawn("forgotten", || value = 42)?);
                        Ok(())
                    })
                    .unwrap();
                    assert_eq!(value, 42);
                })?
                .join()
        })
        .unwrap();
}

#[test]
fn completed_local_waits_ignore_later_cancellation_and_remain_idempotent() {
    let runtime = Runtime::new().unwrap();
    runtime
        .run_scope(|scope| {
            scope
                .spawn("parent", || {
                    let result = local_scope(|local| {
                        let mut child = local.spawn("ready child", || 42)?;
                        while !child.is_finished() {
                            crate::yield_now()?;
                        }
                        crate::cancellation_token()?.cancel();
                        child.wait().expect("completed child ignores cancellation");
                        child.wait().expect("completed wait is idempotent");
                        assert_eq!(child.join().unwrap(), 42);
                        child.wait().expect("consumed child stays completed");
                        assert!(matches!(
                            child.take_result(),
                            Err(crate::Error::ResultAlreadyTaken)
                        ));
                        Ok(())
                    });
                    assert!(matches!(
                        result.as_ref().map_err(crate::Error::primary),
                        Err(crate::Error::Cancelled)
                    ));
                })?
                .join()
        })
        .unwrap();
}

#[test]
fn an_incomplete_local_wait_still_observes_cancellation() {
    crate::run(|scope| {
        scope
            .spawn("parent", || {
                let result = local_scope(|local| {
                    let mut child = local.spawn("pending", || 42)?;
                    assert!(!child.is_finished());
                    crate::cancellation_token()?.cancel();
                    assert!(matches!(child.wait(), Err(crate::Error::Cancelled)));
                    assert!(!child.is_finished());
                    Ok(())
                });
                assert!(matches!(
                    result.as_ref().map_err(crate::Error::primary),
                    Err(crate::Error::Cancelled)
                ));
            })?
            .join()
    })
    .unwrap();
}