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
284
285
286
287
288
289
290
291
292
293
/*
 * Copyright (c) Dell Inc., or its subsidiaries. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 */
#![deny(
    clippy::all,
    clippy::cargo,
    clippy::else_if_without_else,
    clippy::empty_line_after_outer_attr,
    clippy::multiple_inherent_impl,
    clippy::mut_mut,
    clippy::path_buf_push_overwrite
)]
#![warn(
    clippy::cargo_common_metadata,
    clippy::mutex_integer,
    clippy::needless_borrow,
    clippy::similar_names
)]
#![allow(clippy::multiple_crate_versions)]

use futures_intrusive::sync::{GenericSemaphoreReleaser, Semaphore};
use std::cmp::min;
use std::sync::Arc;
use tokio::sync::mpsc::error::SendError;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};

pub struct ChannelSender<T> {
    sender: UnboundedSender<(T, usize)>,
    semaphore: Arc<Semaphore>,
    capacity: usize,
}

impl<T> ChannelSender<T> {
    pub async fn send(&self, message: (T, usize)) -> Result<(), SendError<(T, usize)>> {
        let size = message.1;
        let n_permits = min(size, self.capacity);
        let mut result = self.semaphore.acquire(n_permits).await;
        //disable the automatically drop
        GenericSemaphoreReleaser::disarm(&mut result);
        self.sender.send(message)?;
        Ok(())
    }

    pub fn send_without_bp(&self, message: T) -> Result<(), SendError<(T, usize)>> {
        self.sender.send((message, 0))?;
        Ok(())
    }

    pub fn remain(&self) -> usize {
        self.semaphore.permits()
    }
}

impl<T> Clone for ChannelSender<T> {
    fn clone(&self) -> ChannelSender<T> {
        ChannelSender {
            sender: self.sender.clone(),
            semaphore: self.semaphore.clone(),
            capacity: self.capacity,
        }
    }
}

pub struct ChannelReceiver<T> {
    receiver: UnboundedReceiver<(T, usize)>,
    semaphore: Arc<Semaphore>,
    capacity: usize,
}

impl<T> ChannelReceiver<T> {
    pub async fn recv(&mut self) -> Option<(T, CapacityGuard)> {
        let message = self.receiver.recv().await;
        if let Some(msg) = message {
            let size = msg.1;
            let n_permits = min(size, self.capacity);
            let guard = CapacityGuard {
                semaphore: self.semaphore.clone(),
                size: n_permits,
            };
            Some((msg.0, guard))
        } else {
            None
        }
    }
}

pub fn create_channel<U>(capacity: usize) -> (ChannelSender<U>, ChannelReceiver<U>) {
    let (tx, rx) = unbounded_channel();
    let semaphore = Semaphore::new(true, capacity);
    let semaphore_arc = Arc::new(semaphore);
    let sender = ChannelSender {
        sender: tx,
        semaphore: semaphore_arc.clone(),
        capacity,
    };
    let receiver = ChannelReceiver {
        receiver: rx,
        semaphore: semaphore_arc,
        capacity,
    };
    (sender, receiver)
}

pub struct CapacityGuard {
    semaphore: Arc<Semaphore>,
    pub size: usize,
}

impl Drop for CapacityGuard {
    fn drop(&mut self) {
        self.semaphore.release(self.size);
    }
}

#[cfg(test)]
mod tests {
    use super::create_channel;
    use std::time;
    use tokio::runtime::Runtime;

    #[test]
    fn test_wrapper() {
        let runtime = Runtime::new().unwrap();
        runtime.block_on(test_simple_test());
        runtime.block_on(test_send_order());
        runtime.block_on(test_sender_block());
        runtime.block_on(test_sender_close_first());
        runtime.block_on(test_receiver_close_first());
        runtime.block_on(test_guard_drop());
    }

    async fn test_simple_test() {
        // can only hold 4 bytes
        let (tx, mut rx) = create_channel(4);

        tokio::spawn(async move {
            if let Err(_) = tx.send((1, 4)).await {
                println!("receiver dropped");
            }
        });

        if let Some(i) = rx.recv().await {
            assert_eq!(i.0, 1);
        } else {
            panic!("Test failed");
        }
    }

    async fn test_send_order() {
        // can only hold 4 bytes
        let (tx, mut rx) = create_channel(8);

        let tx1 = tx.clone();
        tokio::spawn(async move {
            tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
            if let Err(_) = tx1.send((1, 4)).await {
                println!("receiver dropped");
            }
        });

        let tx2 = tx.clone();
        tokio::spawn(async move {
            if let Err(_) = tx2.send((2, 4)).await {
                println!("receiver dropped");
            }
        });

        // 2 should come first.
        if let Some(i) = rx.recv().await {
            assert_eq!(i.0, 2);
        } else {
            panic!("test failed");
        }

        if let Some(i) = rx.recv().await {
            assert_eq!(i.0, 1);
        } else {
            panic!("test failed");
        }
    }

    async fn test_sender_block() {
        // can only hold 7 bytes
        let (tx, mut rx) = create_channel(7);

        let tx1 = tx.clone();
        // need 4 bytes.
        tokio::spawn(async move {
            if let Err(_) = tx1.send((1, 4)).await {
                println!("receiver dropped");
            }
        });

        // need another 4 bytes. (will block)
        let tx2 = tx.clone();
        tokio::spawn(async move {
            if let Err(_) = tx2.send((2, 4)).await {
                println!("receiver dropped");
            }
        });

        if let Some(message) = rx.recv().await {
            match message {
                (1, guard) => {
                    drop(guard);
                    let (second, _) = rx.recv().await.expect("get second message");
                    assert_eq!(second, 2);
                }
                (2, guard) => {
                    drop(guard);
                    let (second, _) = rx.recv().await.expect("get first message");
                    assert_eq!(second, 1);
                }
                _ => panic!("test failed"),
            }
        } else {
            panic!("test failed");
        }
    }

    async fn test_sender_close_first() {
        let (tx, mut rx) = create_channel(100);

        // tx would drop in this thread
        tokio::spawn(async move {
            for i in 0..10 {
                if let Err(_) = tx.send((i, 4)).await {
                    println!("receiver dropped");
                    return;
                }
            }
        });

        for i in 0..10 {
            if let Some(j) = rx.recv().await {
                assert_eq!(i, j.0);
            }
        }

        // `None` is returned when all `Sender` halves have dropped, indicating
        // that no further values can be sent on the channel.
        if let None = rx.recv().await {
            println!("Test passed");
        } else {
            panic!("Test failed");
        }
    }

    async fn test_receiver_close_first() {
        let (tx, mut rx) = create_channel(100);
        tx.send((1, 4)).await.expect("send message to channel");

        tokio::spawn(async move {
            if let Some(i) = rx.recv().await {
                assert_eq!(i.0, 1);
                return;
            }
        });
        tokio::time::sleep(time::Duration::from_secs(1)).await;
        let result = tx.send((2, 4)).await;
        assert!(result.is_err());
    }

    async fn test_guard_drop() {
        let (tx, mut rx) = create_channel(100);
        tx.send((10, 10)).await.expect("send message to channel");
        tx.send((20, 20)).await.expect("send message to channel");
        tx.send((30, 30)).await.expect("send message to channel");
        tx.send((40, 40)).await.expect("send message to channel");
        assert_eq!(tx.remain(), 0);

        let mut guards = vec![];
        for _i in 0..4 {
            if let Some((event, guard)) = rx.recv().await {
                guards.push((event, guard));
            }
        }

        guards.reverse();
        let mut cap = 0;
        for (event, guard) in guards {
            drop(guard);
            cap += event;
            assert_eq!(tx.remain(), cap);
        }
    }
}