richat_shared/
shutdown.rs

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
use std::{
    collections::BTreeMap,
    future::Future,
    pin::Pin,
    sync::{Arc, Mutex, MutexGuard},
    task::{Context, Poll, Waker},
};

#[derive(Debug)]
pub struct Shutdown {
    state: Arc<Mutex<State>>,
    id: u64,
}

impl Shutdown {
    pub fn new() -> Self {
        let mut state = State {
            shutdown: false,
            map: BTreeMap::new(),
        };
        let id = state.get_next_id();
        state.map.insert(id, None);

        Self {
            state: Arc::new(Mutex::new(state)),
            id,
        }
    }

    fn state_lock(&self) -> MutexGuard<'_, State> {
        match self.state.lock() {
            Ok(guard) => guard,
            Err(error) => error.into_inner(),
        }
    }

    pub fn shutdown(&self) {
        let mut state = self.state_lock();
        state.shutdown = true;
        for value in state.map.values_mut() {
            if let Some(waker) = value.take() {
                waker.wake();
            }
        }
    }

    pub fn is_set(&self) -> bool {
        self.state_lock().shutdown
    }
}

impl Default for Shutdown {
    fn default() -> Self {
        Self::new()
    }
}

impl Clone for Shutdown {
    fn clone(&self) -> Self {
        let mut state = self.state_lock();
        let id = state.get_next_id();
        state.map.insert(id, None);

        Self {
            state: Arc::clone(&self.state),
            id,
        }
    }
}

impl Drop for Shutdown {
    fn drop(&mut self) {
        let mut state = self.state_lock();
        state.map.remove(&self.id);
    }
}

impl Future for Shutdown {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let me = self.as_ref().get_ref();
        let mut state = me.state_lock();

        if state.shutdown {
            return Poll::Ready(());
        }

        state.map.insert(self.id, Some(cx.waker().clone()));
        Poll::Pending
    }
}

#[derive(Debug)]
struct State {
    shutdown: bool,
    map: BTreeMap<u64, Option<Waker>>,
}

impl State {
    fn get_next_id(&self) -> u64 {
        let next_id = self.map.len() as u64;
        if self.map.is_empty() || self.map.last_key_value().map(|(k, _v)| *k + 1) == Some(next_id) {
            next_id
        } else {
            for (index, key) in (0..u64::MAX).zip(self.map.keys()) {
                if index != *key {
                    return index;
                }
            }
            unreachable!()
        }
    }
}