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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use std::{
    cell::RefCell,
    future::Future,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc, Condvar, Mutex,
    },
    task::{Context, Poll, Waker},
    time::Duration,
};
struct Parker {
    unparker: Unparker,
}
const EMPTY: usize = 0;
const PARKED: usize = 1;
const NOTIFIED: usize = 2;

struct Inner {
    state: AtomicUsize,
    lock: Mutex<()>,
    cvar: Condvar,
}

impl Parker {
    fn new() -> Self {
        Self {
            unparker: Unparker {
                inner: Arc::new(Inner {
                    state: AtomicUsize::new(EMPTY),
                    lock: Mutex::new(()),
                    cvar: Condvar::new(),
                }),
            },
        }
    }

    fn park(&self) {
        self.unparker.inner.park(None);
    }

    //pub fn park_timeout(&self, timeout: Duration) {
    //    self.unparker.inner.park(Some(timeout));
    //}

    //pub fn unparker(&self) -> &Unparker {
    //    &self.unparker
    //}
}

struct Unparker {
    inner: Arc<Inner>,
}

unsafe impl Send for Parker {}

impl Unparker {
    pub fn unpark(&self) {
        self.inner.unpark()
    }
}
unsafe impl Send for Unparker {}
unsafe impl Sync for Unparker {}

impl Clone for Unparker {
    fn clone(&self) -> Unparker {
        Unparker {
            inner: self.inner.clone(),
        }
    }
}

impl Inner {
    fn park(&self, timeout: Option<Duration>) {
        if self
            .state
            .compare_exchange(NOTIFIED, EMPTY, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
        {
            return;
        }

        if let Some(ref dur) = timeout {
            if *dur == Duration::from_millis(0) {
                return;
            }
        }

        let mut m = self.lock.lock().unwrap();
        match self
            .state
            .compare_exchange(EMPTY, PARKED, Ordering::SeqCst, Ordering::SeqCst)
        {
            Ok(_) => {}
            Err(NOTIFIED) => {
                let _old = self.state.swap(EMPTY, Ordering::SeqCst);
                return;
            }
            Err(_) => panic!("invalid park state"),
        }

        match timeout {
            None => loop {
                m = self.cvar.wait(m).unwrap();
                if self
                    .state
                    .compare_exchange(NOTIFIED, EMPTY, Ordering::SeqCst, Ordering::SeqCst)
                    .is_ok()
                {
                    return;
                }
            },
            Some(timeout) => {
                let (_m, _result) = self.cvar.wait_timeout(m, timeout).unwrap();
                match self.state.swap(EMPTY, Ordering::SeqCst) {
                    NOTIFIED => {}
                    PARKED => {}
                    n => panic!("invalid park state {}", n),
                }
            }
        }
    }

    fn unpark(&self) {
        match self.state.swap(NOTIFIED, Ordering::SeqCst) {
            EMPTY => return,
            NOTIFIED => return,
            PARKED => {}
            _ => panic!("invalid park state"),
        }

        drop(self.lock.lock().unwrap());
        self.cvar.notify_one();
    }
}

/// Run a future to completion, sleeping the thread if there is no progress that can be made.
pub fn block_on<T>(future: impl Future<Output = T>) -> T {
    thread_local! {
        static CACHE: RefCell<(Parker, Waker)> = {
            let parker = Parker::new();
            let unparker = parker.unparker.clone();
            let waker = async_task::waker_fn(move || unparker.unpark());
            RefCell::new((parker, waker))
        };
    }

    CACHE.with(|cache| {
        let (parker, waker) = &mut *cache.try_borrow_mut().expect("recursive block_on");
        crate::run::enter(|| {
            futures_util::pin_mut!(future);
            let cx = &mut Context::from_waker(waker);
            loop {
                match future.as_mut().poll(cx) {
                    Poll::Ready(output) => return output,
                    Poll::Pending => parker.park(),
                }
            }
        })
    })
}