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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use std::{cell::RefCell, rc::Rc};

use crate::{
    buf::{IoBuf, IoBufMut},
    io::WriteOwned,
    BufResult,
};
use tokio::sync::mpsc;

use super::ReadOwned;

/// Allows sending `Vec<u8>` chunks, which can be read through its [ReadOwned]
/// implementation.
pub struct ChanRead {
    inner: Rc<ChanReadInner>,
}

pub struct ChanReadSend {
    inner: Rc<ChanReadInner>,
}

struct ChanReadInner {
    notify: tokio::sync::Notify,
    guarded: RefCell<ChanReadGuarded>,
}

struct ChanReadGuarded {
    state: ChanReadState,
    pos: usize,
    buf: Vec<u8>,
}

enum ChanReadState {
    // Data may still come in
    Live,

    // [ChanReaderSend] was dropped, no more data is coming
    Eof,

    // [ChanReaderSend::rest] was called
    Reset,
}

impl ChanRead {
    pub fn new() -> (ChanReadSend, Self) {
        let inner = Rc::new(ChanReadInner {
            notify: Default::default(),
            guarded: RefCell::new(ChanReadGuarded {
                state: ChanReadState::Live,
                pos: 0,
                buf: Vec::new(),
            }),
        });
        (
            ChanReadSend {
                inner: inner.clone(),
            },
            Self { inner },
        )
    }
}

impl ChanReadSend {
    /// Sever this connection abnormally - read will eventually return [std::io::ErrorKind::ConnectionReset]
    pub fn reset(self) {
        let mut guarded = self.inner.guarded.borrow_mut();
        guarded.state = ChanReadState::Reset;
        // let it drop, which will notify waiters
    }

    /// Send a chunk of data. Readers will not be able to read _more_ than the
    /// length of this chunk in a single call, but may read less (if their buffer
    /// is too small).
    pub async fn send(&self, next_buf: impl Into<Vec<u8>>) -> Result<(), std::io::Error> {
        let next_buf = next_buf.into();

        loop {
            {
                let mut guarded = self.inner.guarded.borrow_mut();
                match guarded.state {
                    ChanReadState::Live => {
                        if guarded.pos == guarded.buf.len() {
                            guarded.pos = 0;
                            guarded.buf = next_buf;
                            self.inner.notify.notify_waiters();
                            return Ok(());
                        } else {
                            // wait for read
                        }
                    }

                    // can't send after dropping
                    ChanReadState::Eof => unreachable!(),

                    // can't send after calling abort
                    ChanReadState::Reset => unreachable!(),
                }
            }
            self.inner.notify.notified().await
        }
    }
}

impl Drop for ChanReadSend {
    fn drop(&mut self) {
        let mut guarded = self.inner.guarded.borrow_mut();
        if let ChanReadState::Live = guarded.state {
            guarded.state = ChanReadState::Eof;
        }
        self.inner.notify.notify_waiters();
    }
}

impl ReadOwned for ChanRead {
    async fn read<B: IoBufMut>(&mut self, mut buf: B) -> BufResult<usize, B> {
        let out =
            unsafe { std::slice::from_raw_parts_mut(buf.stable_mut_ptr(), buf.bytes_total()) };

        loop {
            {
                let mut guarded = self.inner.guarded.borrow_mut();
                let remain = guarded.buf.len() - guarded.pos;

                if remain > 0 {
                    let n = std::cmp::min(remain, out.len());

                    out[..n].copy_from_slice(&guarded.buf[guarded.pos..guarded.pos + n]);
                    guarded.pos += n;

                    self.inner.notify.notify_waiters();

                    unsafe {
                        buf.set_init(n);
                    }
                    return (Ok(n), buf);
                }

                match guarded.state {
                    ChanReadState::Live => {
                        // muffin
                    }
                    ChanReadState::Eof => {
                        return (Ok(0), buf);
                    }
                    ChanReadState::Reset => {
                        return (Err(std::io::ErrorKind::ConnectionReset.into()), buf);
                    }
                }
            }

            self.inner.notify.notified().await;
        }
    }
}

pub struct ChanWrite {
    tx: mpsc::Sender<Vec<u8>>,
}

impl ChanWrite {
    pub fn new() -> (mpsc::Receiver<Vec<u8>>, Self) {
        let (tx, rx) = mpsc::channel(1);
        (rx, Self { tx })
    }
}

impl WriteOwned for ChanWrite {
    async fn write<B: IoBuf>(&mut self, buf: B) -> BufResult<usize, B> {
        let slice = unsafe { std::slice::from_raw_parts(buf.stable_ptr(), buf.bytes_init()) };
        match self.tx.send(slice.to_vec()).await {
            Ok(()) => (Ok(buf.bytes_init()), buf),
            Err(_) => (Err(std::io::ErrorKind::BrokenPipe.into()), buf),
        }
    }
}

#[cfg(all(test, not(feature = "miri")))]
mod tests {
    use super::{ChanRead, ReadOwned};
    use std::{cell::RefCell, rc::Rc};

    #[test]
    fn test_chan_reader() {
        crate::start(async move {
            let (send, mut cr) = ChanRead::new();
            let wrote_three = Rc::new(RefCell::new(false));

            crate::spawn({
                let wrote_three = wrote_three.clone();
                async move {
                    send.send("one").await.unwrap();
                    send.send("two").await.unwrap();
                    send.send("three").await.unwrap();
                    *wrote_three.borrow_mut() = true;
                    send.send("splitread").await.unwrap();
                }
            });

            {
                let buf = vec![0u8; 256];
                let (res, buf) = cr.read(buf).await;
                let n = res.unwrap();
                assert_eq!(&buf[..n], b"one");
            }

            assert!(!*wrote_three.borrow());

            {
                let buf = vec![0u8; 256];
                let (res, buf) = cr.read(buf).await;
                let n = res.unwrap();
                assert_eq!(&buf[..n], b"two");
            }

            tokio::task::yield_now().await;
            assert!(*wrote_three.borrow());

            {
                let buf = vec![0u8; 256];
                let (res, buf) = cr.read(buf).await;
                let n = res.unwrap();
                assert_eq!(&buf[..n], b"three");
            }

            {
                let buf = vec![0u8; 5];
                let (res, buf) = cr.read(buf).await;
                let n = res.unwrap();
                assert_eq!(&buf[..n], b"split");

                let buf = vec![0u8; 256];
                let (res, buf) = cr.read(buf).await;
                let n = res.unwrap();
                assert_eq!(&buf[..n], b"read");
            }

            {
                let buf = vec![0u8; 0];
                let (res, _) = cr.read(buf).await;
                let n = res.unwrap();
                assert_eq!(n, 0, "reached EOF");
            }

            let (send, mut cr) = ChanRead::new();

            crate::spawn({
                async move {
                    send.send("two-part").await.unwrap();
                    send.reset();
                }
            });

            for _ in 0..5 {
                tokio::task::yield_now().await;
            }

            {
                let buf = vec![0u8; 4];
                let (res, buf) = cr.read(buf).await;
                let n = res.unwrap();
                assert_eq!(&buf[..n], b"two-");
            }

            {
                let buf = vec![0u8; 4];
                let (res, buf) = cr.read(buf).await;
                let n = res.unwrap();
                assert_eq!(&buf[..n], b"part");
            }

            {
                let buf = vec![0u8; 0];
                let (res, _) = cr.read(buf).await;
                let err = res.unwrap_err();
                assert_eq!(
                    err.kind(),
                    std::io::ErrorKind::ConnectionReset,
                    "reached EOF"
                );
            }
        })
    }
}