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

use pin_project_lite::pin_project;

use crate::reactive::StreamError;

use super::Subscriber;

pin_project! {
    /// A unbounded subscriber.
    pub struct Unbounded<F> {
        f: F,
    }
}

#[cfg(not(feature = "send"))]
impl<I, F> Subscriber<I> for Unbounded<F>
where
    F: FnMut(Result<I, StreamError>),
{
    fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<bool, StreamError>> {
        Poll::Ready(Ok(true))
    }

    fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), StreamError> {
        (self.project().f)(Ok(item));
        Ok(())
    }

    fn closing(self: Pin<&mut Self>, reason: Result<(), StreamError>) -> Result<(), StreamError> {
        if let Err(err) = reason {
            (self.project().f)(Err(err));
        }
        Ok(())
    }

    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), StreamError>> {
        Poll::Ready(Ok(()))
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<bool, StreamError>> {
        Poll::Ready(Ok(true))
    }
}

#[cfg(feature = "send")]
impl<I, F> Subscriber<I> for Unbounded<F>
where
    F: FnMut(Result<I, StreamError>) + Send,
{
    fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<bool, StreamError>> {
        Poll::Ready(Ok(true))
    }

    fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), StreamError> {
        (self.project().f)(Ok(item));
        Ok(())
    }

    fn closing(self: Pin<&mut Self>, reason: Result<(), StreamError>) -> Result<(), StreamError> {
        if let Err(err) = reason {
            (self.project().f)(Err(err));
        }
        Ok(())
    }

    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), StreamError>> {
        Poll::Ready(Ok(()))
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<bool, StreamError>> {
        Poll::Ready(Ok(true))
    }
}

/// Create a unbounded subscriber.
pub fn unbounded<I, F>(f: F) -> Unbounded<F>
where
    F: FnMut(Result<I, StreamError>) + Send,
{
    Unbounded { f }
}