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
//! A channel specifically for sending/receiving batches of bytes.

#![allow(dead_code)]

use std::sync::{Arc, Mutex};

use bytes::BytesMut;
use thiserror::Error;
use tokio::sync::Notify;

pub(crate) fn byte_channel(limit: usize) -> (ByteSender, ByteReceiver) {
    let shared = Arc::new(Shared {
        mtx: Mutex::new(Inner {
            bytes: BytesMut::new(),
            disconnected: false,
        }),
        notify: Notify::new(),
        limit,
    });

    let sender = ByteSender {
        shared: shared.clone(),
    };

    let receiver = ByteReceiver { shared };

    (sender, receiver)
}

pub(crate) struct ByteSender {
    shared: Arc<Shared>,
}

pub(crate) struct ByteReceiver {
    shared: Arc<Shared>,
}

struct Shared {
    mtx: Mutex<Inner>,
    notify: Notify,
    limit: usize,
}

struct Inner {
    bytes: BytesMut,
    disconnected: bool,
}

impl ByteSender {
    pub(crate) fn take_capacity(&mut self, additional: usize) -> BytesMut {
        let mut lck = self.shared.mtx.lock().unwrap();

        lck.bytes.reserve(additional);

        let len = lck.bytes.len();
        lck.bytes.split_off(len)
    }

    pub(crate) fn try_send(&mut self, mut bytes: BytesMut) -> Result<(), TrySendError> {
        let mut lck = self.shared.mtx.lock().unwrap();

        if lck.disconnected {
            return Err(TrySendError::Disconnected(bytes));
        }

        if bytes.is_empty() {
            return Ok(());
        }

        let available = self.shared.limit - lck.bytes.len();

        if bytes.len() > available {
            if available > 0 {
                lck.bytes.unsplit(bytes.split_to(available));
                self.shared.notify.notify_waiters();
            }

            return Err(TrySendError::Full(bytes));
        }

        lck.bytes.unsplit(bytes);
        self.shared.notify.notify_waiters();

        Ok(())
    }

    pub(crate) async fn send_async(&mut self, mut bytes: BytesMut) -> Result<(), SendError> {
        loop {
            {
                let mut lck = self.shared.mtx.lock().unwrap();

                if lck.disconnected {
                    return Err(SendError(bytes));
                }

                if bytes.is_empty() {
                    return Ok(());
                }

                let available = self.shared.limit - lck.bytes.len();

                if bytes.len() <= available {
                    lck.bytes.unsplit(bytes);
                    self.shared.notify.notify_waiters();
                    return Ok(());
                }

                if available > 0 {
                    lck.bytes.unsplit(bytes.split_to(available));
                    self.shared.notify.notify_waiters();
                }
            }

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

    pub(crate) fn is_disconnected(&self) -> bool {
        self.shared.mtx.lock().unwrap().disconnected
    }

    pub(crate) fn limit(&self) -> usize {
        self.shared.limit
    }
}

/// Contains any excess bytes not sent.
#[derive(Clone, PartialEq, Eq, Debug, Error)]
pub(crate) enum TrySendError {
    #[error("sender disconnected")]
    Disconnected(BytesMut),
    #[error("channel full (see `Config::outgoing_capacity`)")]
    Full(BytesMut),
}

#[derive(Clone, PartialEq, Eq, Debug, Error)]
#[error("sender disconnected")]
pub(crate) struct SendError(pub(crate) BytesMut);

impl SendError {
    pub(crate) fn into_inner(self) -> BytesMut {
        self.0
    }
}

impl ByteReceiver {
    pub(crate) fn try_recv(&mut self) -> Result<BytesMut, TryRecvError> {
        let mut lck = self.shared.mtx.lock().unwrap();

        if !lck.bytes.is_empty() {
            self.shared.notify.notify_waiters();
            return Ok(lck.bytes.split());
        }

        if lck.disconnected {
            return Err(TryRecvError::Disconnected);
        }

        Err(TryRecvError::Empty)
    }

    pub(crate) async fn recv_async(&mut self) -> Result<BytesMut, RecvError> {
        loop {
            {
                let mut lck = self.shared.mtx.lock().unwrap();

                if !lck.bytes.is_empty() {
                    self.shared.notify.notify_waiters();
                    return Ok(lck.bytes.split());
                }

                if lck.disconnected {
                    return Err(RecvError::Disconnected);
                }
            }

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

    pub(crate) fn is_disconnected(&self) -> bool {
        self.shared.mtx.lock().unwrap().disconnected
    }

    pub(crate) fn limit(&self) -> usize {
        self.shared.limit
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Debug, Error)]
pub(crate) enum TryRecvError {
    #[error("empty channel")]
    Empty,
    #[error("receiver disconnected")]
    Disconnected,
}

#[derive(Copy, Clone, PartialEq, Eq, Debug, Error)]
pub(crate) enum RecvError {
    #[error("receiver disconnected")]
    Disconnected,
}

impl Drop for ByteSender {
    fn drop(&mut self) {
        self.shared.mtx.lock().unwrap().disconnected = true;
    }
}

impl Drop for ByteReceiver {
    fn drop(&mut self) {
        self.shared.mtx.lock().unwrap().disconnected = true;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn byte_channel_try() {
        let (mut sender, mut receiver) = byte_channel(4);

        assert_eq!(
            sender.try_send("hello".as_bytes().into()),
            Err(TrySendError::Full("o".as_bytes().into()))
        );

        assert_eq!(
            receiver.try_recv().unwrap(),
            BytesMut::from("hell".as_bytes())
        );
    }

    #[tokio::test]
    async fn byte_channel_async() {
        let (mut sender, mut receiver) = byte_channel(4);

        let t = tokio::spawn(async move {
            let bytes = receiver.recv_async().await.unwrap();
            assert_eq!(&bytes[..], b"hell");
            let bytes = receiver.recv_async().await.unwrap();
            assert_eq!(&bytes[..], b"o");

            assert_eq!(receiver.try_recv(), Err(TryRecvError::Empty));
        });

        sender.send_async("hello".as_bytes().into()).await.unwrap();

        t.await.unwrap();

        assert!(sender.is_disconnected());
    }
}