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
use core::{
    pin::Pin,
    task::{Context, Poll},
};
use futures::Stream;

pub trait Interrupt {
    type Error;

    fn enable(&mut self) -> Result<(), Self::Error>;

    fn disable(&mut self) -> Result<(), Self::Error>;

    fn poll_interrupt(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>>;

    fn poll_interrupt_unpin(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>>
    where
        Self: Unpin,
    {
        Pin::new(self).poll_interrupt(cx)
    }

    /// Enable the interrupt and return a [`Stream`] of events.
    /// This will disable the interrupt on drop.
    fn interrupts(&mut self) -> Interrupts<Self>
    where
        Self: Unpin,
    {
        Interrupts {
            interrupt: self,
            is_enabled: false,
        }
    }
}

pub struct Interrupts<'a, T: Interrupt + ?Sized> {
    interrupt: &'a mut T,
    is_enabled: bool,
}

impl<T> Stream for Interrupts<'_, T>
where
    T: Interrupt + Unpin + ?Sized,
{
    type Item = Result<(), T::Error>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if !self.is_enabled {
            self.interrupt.enable()?;
            self.is_enabled = true;
        }

        self.interrupt.poll_interrupt_unpin(cx).map(Some)
    }
}

impl<T> Drop for Interrupts<'_, T>
where
    T: Interrupt + ?Sized,
{
    fn drop(&mut self) {
        self.interrupt.disable().ok();
    }
}