futures_signals/signal/
channel.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
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
use super::Signal;
use std::pin::Pin;
use std::marker::Unpin;
use std::sync::{Arc, Weak};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Poll, Context, Waker};
use crate::atomic::AtomicOption;


#[derive(Debug)]
struct Inner<A> {
    value: AtomicOption<A>,
    // TODO use AtomicWaker ?
    waker: AtomicOption<Waker>,
    senders: AtomicUsize,
}

impl<A> Inner<A> {
    #[inline]
    fn has_senders(&self) -> bool {
        // This will be 0 if the channel was closed
        self.senders.load(Ordering::Acquire) != 0
    }

    #[inline]
    fn add_sender(&self) {
        self.senders.fetch_add(1, Ordering::AcqRel);
    }

    /// Returns `true` if it no longer has any senders
    #[inline]
    fn remove_sender(&self) -> bool {
        self.senders.fetch_sub(1, Ordering::AcqRel) == 1
    }

    #[inline]
    fn remove_all_senders(&self) {
        self.senders.store(0, Ordering::Release);
    }

    fn notify(&self) {
        if let Some(waker) = self.waker.take() {
            waker.wake();
        }
    }
}


#[derive(Debug)]
pub struct Sender<A> {
    inner: Weak<Inner<A>>,
}

impl<A> Sender<A> {
    pub fn send(&self, value: A) -> Result<(), A> {
        if let Some(inner) = self.inner.upgrade() {
            if inner.has_senders() {
                inner.value.store(Some(value));
                inner.notify();
                Ok(())

            } else {
                Err(value)
            }

        } else {
            Err(value)
        }
    }

    pub fn close(&self) {
        if let Some(inner) = self.inner.upgrade() {
            if inner.has_senders() {
                inner.remove_all_senders();
                inner.notify();
            }
        }
    }
}

impl<A> Clone for Sender<A> {
    fn clone(&self) -> Self {
        if let Some(inner) = self.inner.upgrade() {
            // This might be `false` if the `close` method was called
            if inner.has_senders() {
                inner.add_sender();
            }
        }

        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<A> Drop for Sender<A> {
    fn drop(&mut self) {
        if let Some(inner) = self.inner.upgrade() {
            // This might be `false` if the `close` method was called
            if inner.has_senders() {
                // If there aren't any more senders...
                if inner.remove_sender() {
                    inner.notify();
                }
            }
        }
    }
}


#[derive(Debug)]
#[must_use = "Signals do nothing unless polled"]
pub struct Receiver<A> {
    inner: Arc<Inner<A>>,
}

impl<A> Unpin for Receiver<A> {}

impl<A> Signal for Receiver<A> {
    type Item = A;

    #[inline]
    fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        match self.inner.value.take() {
            None => {
                if self.inner.has_senders() {
                    self.inner.waker.store(Some(cx.waker().clone()));
                    Poll::Pending

                } else {
                    Poll::Ready(None)
                }
            },

            a => Poll::Ready(a),
        }
    }
}

pub fn channel<A>(initial_value: A) -> (Sender<A>, Receiver<A>) {
    let inner = Arc::new(Inner {
        value: AtomicOption::new(Some(initial_value)),
        waker: AtomicOption::new(None),
        senders: AtomicUsize::new(1),
    });

    let sender = Sender {
        inner: Arc::downgrade(&inner),
    };

    let receiver = Receiver {
        inner,
    };

    (sender, receiver)
}