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
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum SendStatus {
    Success,
    Failure,
}
impl From<bool> for SendStatus {
    fn from(success: bool) -> Self {
        if success {
            Self::Success
        } else {
            Self::Failure
        }
    }
}

impl SendStatus {
    pub fn is_success(self) -> bool {
        SendStatus::Success == self
    }
}

#[derive(Default)]
pub(crate) struct AfterSend(Option<Box<dyn FnOnce(SendStatus) + Send + Sync + 'static>>);

impl AfterSend {
    pub(crate) fn call(&mut self, send_status: SendStatus) {
        if let Some(after_send) = self.0.take() {
            after_send(send_status);
        }
    }

    pub(crate) fn append<F>(&mut self, after_send: F)
    where
        F: FnOnce(SendStatus) + Send + Sync + 'static,
    {
        self.0 = Some(match self.0.take() {
            Some(existing_after_send) => Box::new(move |ss| {
                existing_after_send(ss);
                after_send(ss);
            }),
            None => Box::new(after_send),
        });
    }
}

impl Drop for AfterSend {
    fn drop(&mut self) {
        self.call(SendStatus::Failure);
    }
}