1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::cell::Cell;

use thiserror::Error as ThisError;

thread_local! (static EXECUTOR_ACTIVE: Cell<bool> = Cell::new(false));

#[derive(ThisError, Debug)]
#[error("Nested execution is not supported")]
struct NestedExecutionNotSupported;

#[derive(Debug)]
pub struct ExecutionGuard;

impl Drop for ExecutionGuard {
    fn drop(&mut self) {
        EXECUTOR_ACTIVE.with(|active| {
            assert!(active.get());
            active.set(false);
        })
    }
}

pub fn enter() -> anyhow::Result<ExecutionGuard> {
    EXECUTOR_ACTIVE.with(|active| {
        if active.get() {
            Err(NestedExecutionNotSupported.into())
        } else {
            active.set(true);

            Ok(ExecutionGuard)
        }
    })
}

#[cfg(test)]
mod test {
    use super::NestedExecutionNotSupported;
    use crate::Executor;

    #[test]
    fn nested_execution() {
        Executor::new()
            .run_until(async {
                let e = Executor::new()
                    .run_until(async {})
                    .expect_err("nested execution successful");
                e.downcast::<NestedExecutionNotSupported>()
                    .expect("unexpected error type");
            })
            .unwrap();

        let ex = Executor::new();
        ex.run_until(async {
            let e = ex
                .run_until(async {})
                .expect_err("nested execution successful");
            e.downcast::<NestedExecutionNotSupported>()
                .expect("unexpected error type");
        })
        .unwrap();
    }
}