-
Notifications
You must be signed in to change notification settings - Fork 32
/
lib.rs
689 lines (652 loc) · 23 KB
/
lib.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! # Kanal: The fast synchronous and asynchronous channel that Rust deserves.
//!
//! Kanal is a Rust library to help programmers design effective programs in CSP model via providing featureful multi-producer multi-consumer channels.
//! This library focuses on bringing both sync and async API together to unify message passing between sync and async parts of Rust code in a performant manner.
//! Performance is the main goal of Kanal.
//!
//!
#[cfg(feature = "async")]
mod future;
#[cfg(feature = "async")]
use future::*;
pub(crate) mod internal;
mod kanal_tests;
pub(crate) mod mutex;
mod signal;
pub(crate) mod state;
use internal::{acquire_internal, ChannelInternal, Internal};
use std::{
mem::{ManuallyDrop, MaybeUninit},
time::{Duration, SystemTime},
};
use std::fmt;
use signal::{AsyncSignal, SyncSignal};
/*
use crate::mutex::MutexGuard;
#[inline(always)]
fn acquire_internal<'a, T>(internal: &'a Internal<T>) -> MutexGuard<'a, ChannelInternal<T>> {
internal.lock()
}*/
// Error states in channel
#[derive(Debug)]
pub enum Error {
Closed,
SendClosed,
ReceiveClosed,
}
impl std::error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match *self {
Error::Closed => "channel is closed",
Error::SendClosed => "channel send side is closed",
Error::ReceiveClosed => "channel receive side is closed",
}
)
}
}
// Error states in channel
#[derive(Debug)]
pub enum ErrorTimeout {
Closed,
SendClosed,
ReceiveClosed,
Timeout,
}
impl std::error::Error for ErrorTimeout {}
impl fmt::Display for ErrorTimeout {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match *self {
ErrorTimeout::Closed => "channel is closed",
ErrorTimeout::SendClosed => "channel send side is closed",
ErrorTimeout::ReceiveClosed => "channel receive side is closed",
ErrorTimeout::Timeout => "channel operation timeout",
}
)
}
}
// Sync sender of channel for type T, it can generate async version via clone_async
pub struct Sender<T> {
internal: Internal<T>,
}
// Async sender of channel for type T, it can generate sync version via clone_sync
pub struct AsyncSender<T> {
internal: Internal<T>,
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
let mut internal = acquire_internal(&self.internal);
if internal.send_count > 0 {
internal.send_count -= 1;
}
}
}
impl<T> Drop for AsyncSender<T> {
fn drop(&mut self) {
let mut internal = acquire_internal(&self.internal);
if internal.send_count > 0 {
internal.send_count -= 1;
}
}
}
impl<T> Clone for Sender<T> {
fn clone(&self) -> Self {
let mut internal = acquire_internal(&self.internal);
if internal.send_count > 0 {
internal.send_count += 1;
}
Self {
internal: self.internal.clone(),
}
}
}
impl<T> Clone for AsyncSender<T> {
fn clone(&self) -> Self {
let mut internal = acquire_internal(&self.internal);
if internal.send_count > 0 {
internal.send_count += 1;
}
Self {
internal: self.internal.clone(),
}
}
}
macro_rules! shared_impl {
() => {
/// Returns whether channel is bounded or not
pub fn is_bounded(&mut self) -> bool {
acquire_internal(&self.internal).capacity != usize::MAX
}
/// Returns length of the queue
pub fn len(&self) -> usize {
acquire_internal(&self.internal).queue.len()
}
/// Returns whether channel queue is empty or not
pub fn is_empty(&self) -> bool {
acquire_internal(&self.internal).queue.is_empty()
}
/// Returns capacity of channel (not the queue)
/// for unbounded channels it will return usize::MAX
pub fn capacity(&mut self) -> usize {
acquire_internal(&self.internal).capacity
}
// Closes the channel completely and terminates waiters requests
pub fn close(&mut self) {
let mut internal = acquire_internal(&self.internal);
internal.recv_count = 0;
internal.send_count = 0;
internal.terminate_signals();
internal.send_wait.clear();
internal.recv_wait.clear();
}
// Returns whether channel is closed or not
pub fn is_closed(&mut self) -> bool {
let internal = acquire_internal(&self.internal);
internal.send_count == 0 && internal.recv_count == 0
}
};
}
impl<T> Sender<T> {
/// Sends data to the channel
#[inline(always)]
pub fn send(&self, mut data: T) -> Result<(), Error> {
let mut internal = acquire_internal(&self.internal);
if internal.send_count == 0 {
return Err(Error::Closed);
}
if let Some(first) = internal.next_recv() {
drop(internal);
unsafe { first.send(data) }
Ok(())
} else if internal.queue.len() < internal.capacity {
internal.queue.push_back(data);
Ok(())
} else {
if internal.recv_count == 0 {
return Err(Error::ReceiveClosed);
}
// send directly to wait list
let mut sig = SyncSignal::new(&mut data as *mut T, std::thread::current());
internal.push_send(sig.as_signal());
drop(internal);
if !sig.wait() {
return Err(Error::SendClosed);
}
// data semantically is moved so forget about droping it if it requires droping
if std::mem::needs_drop::<T>() {
std::mem::forget(data);
}
Ok(())
}
// if queue is not empty send data
}
/// Sends data to the channel
#[inline(always)]
pub fn send_timeout(&self, mut data: T, duration: Duration) -> Result<(), ErrorTimeout> {
let deadline = SystemTime::now().checked_add(duration).unwrap();
let mut internal = acquire_internal(&self.internal);
if internal.send_count == 0 {
return Err(ErrorTimeout::Closed);
}
if let Some(first) = internal.next_recv() {
drop(internal);
unsafe { first.send(data) }
Ok(())
} else if internal.queue.len() < internal.capacity {
internal.queue.push_back(data);
Ok(())
} else {
if internal.recv_count == 0 {
return Err(ErrorTimeout::ReceiveClosed);
}
// send directly to wait list
let mut sig = SyncSignal::new(&mut data as *mut T, std::thread::current());
let cancelable_sig = sig.as_signal();
internal.push_send(cancelable_sig);
drop(internal);
if !sig.wait_timeout(deadline) {
if sig.is_terminated() {
return Err(ErrorTimeout::SendClosed);
}
{
let mut internal = acquire_internal(&self.internal);
if internal.cancel_send_signal(sig.as_signal()) {
return Err(ErrorTimeout::Timeout);
}
}
// removing receive failed wait for signal response
if !sig.wait() {
return Err(ErrorTimeout::SendClosed);
}
}
// data semantically is moved so forget about droping it if it requires droping
if std::mem::needs_drop::<T>() {
std::mem::forget(data);
}
Ok(())
}
// if queue is not empty send data
}
#[inline(always)]
pub fn send_option_timeout(
&self,
data: &mut Option<T>,
duration: Duration,
) -> Result<(), ErrorTimeout> {
let deadline = SystemTime::now().checked_add(duration).unwrap();
let mut internal = acquire_internal(&self.internal);
if internal.send_count == 0 {
return Err(ErrorTimeout::Closed);
}
if let Some(first) = internal.next_recv() {
drop(internal);
unsafe { first.send(data.take().unwrap()) }
Ok(())
} else if internal.queue.len() < internal.capacity {
internal.queue.push_back(data.take().unwrap());
Ok(())
} else {
if internal.recv_count == 0 {
return Err(ErrorTimeout::ReceiveClosed);
}
// send directly to wait list
let mut d = data.take().unwrap();
let mut sig = SyncSignal::new(&mut d as *mut T, std::thread::current());
internal.push_send(sig.as_signal());
drop(internal);
if !sig.wait_timeout(deadline) {
if sig.is_terminated() {
*data = Some(d);
return Err(ErrorTimeout::SendClosed);
}
{
let mut internal = acquire_internal(&self.internal);
if internal.cancel_send_signal(sig.as_signal()) {
*data = Some(d);
return Err(ErrorTimeout::Timeout);
}
}
// removing receive failed wait for signal response
if !sig.wait() {
*data = Some(d);
return Err(ErrorTimeout::SendClosed);
}
}
Ok(())
}
// if queue is not empty send data
}
/// Tries sending to the channel without waiting in the wait list
/// It returns Ok(true) in case of successful operation and Ok(false) for failed one, or error in case that channel is closed
/// Important note: this function is not lock free as it acquire mutex of channel internal for a short time.
#[inline(always)]
pub fn try_send(&self, data: T) -> Result<bool, Error> {
let mut internal = acquire_internal(&self.internal);
if internal.send_count == 0 {
return Err(Error::Closed);
}
if let Some(first) = internal.next_recv() {
drop(internal);
unsafe { first.send(data) }
return Ok(true);
} else if internal.queue.len() < internal.capacity {
internal.queue.push_back(data);
return Ok(true);
}
Ok(false)
}
/// Clones Sender as async version of it and returns it
pub fn clone_async(&self) -> AsyncSender<T> {
let mut internal = acquire_internal(&self.internal);
if internal.send_count > 0 {
internal.send_count += 1;
}
AsyncSender::<T> {
internal: self.internal.clone(),
}
}
/// Returns whether receive part of channel is closed or not
pub fn is_disconnected(&mut self) -> bool {
acquire_internal(&self.internal).recv_count == 0
}
shared_impl!();
}
#[cfg(feature = "async")]
impl<T> AsyncSender<T> {
/// Sends data asynchronously to the channel
#[inline(always)]
pub fn send(&'_ self, data: T) -> SendFuture<'_, T> {
SendFuture {
state: FutureState::Zero,
internal: &self.internal,
sig: AsyncSignal::new(),
data: ManuallyDrop::new(data),
}
}
/// Tries sending to the channel without waiting in the wait list
/// It returns Ok(true) in case of successful operation and Ok(false) for failed one, or error in case that channel is closed
/// Important note: this function is not lock free as it acquire mutex of channel internal for a short time.
#[inline(always)]
pub fn try_send(&self, data: T) -> Result<bool, Error> {
let mut internal = acquire_internal(&self.internal);
if internal.send_count == 0 {
return Err(Error::Closed);
}
if let Some(first) = internal.next_recv() {
drop(internal);
unsafe { first.send(data) }
return Ok(true);
} else if internal.queue.len() < internal.capacity {
internal.queue.push_back(data);
return Ok(true);
}
Ok(false)
}
#[inline(always)]
pub fn try_send_option(&self, data: &mut Option<T>) -> Result<bool, Error> {
let mut internal = acquire_internal(&self.internal);
if internal.send_count == 0 {
return Err(Error::Closed);
}
if let Some(first) = internal.next_recv() {
drop(internal);
unsafe { first.send(data.take().unwrap()) }
return Ok(true);
} else if internal.queue.len() < internal.capacity {
internal.queue.push_back(data.take().unwrap());
return Ok(true);
}
Ok(false)
}
/// Clones async sender as sync version of it
pub fn clone_sync(&self) -> Sender<T> {
let mut internal = acquire_internal(&self.internal);
if internal.send_count > 0 {
internal.send_count += 1;
}
Sender::<T> {
internal: self.internal.clone(),
}
}
/// Returns whether receive part of channel is closed or not
pub fn is_disconnected(&mut self) -> bool {
acquire_internal(&self.internal).recv_count == 0
}
shared_impl!();
}
pub struct Receiver<T> {
internal: Internal<T>,
}
#[cfg(feature = "async")]
pub struct AsyncReceiver<T> {
internal: Internal<T>,
}
impl<T> Receiver<T> {
/// Receives data from the channel
#[inline(always)]
pub fn recv(&self) -> Result<T, Error> {
let mut internal = acquire_internal(&self.internal);
if internal.recv_count == 0 {
return Err(Error::Closed);
}
if let Some(v) = internal.queue.pop_front() {
if let Some(mut p) = internal.next_send() {
// if there is a sender take its data and push it in queue
unsafe { internal.queue.push_back(p.recv()) }
}
Ok(v)
} else if let Some(mut p) = internal.next_send() {
drop(internal);
unsafe { Ok(p.recv()) }
} else {
if internal.send_count == 0 {
return Err(Error::SendClosed);
}
// no active waiter so push to queue
let mut ret = MaybeUninit::<T>::uninit();
let mut sig = SyncSignal::new(ret.as_mut_ptr(), std::thread::current());
internal.push_recv(sig.as_signal());
drop(internal);
if !sig.wait() {
return Err(Error::ReceiveClosed);
}
Ok(unsafe { ret.assume_init() })
}
// if queue is not empty send data
}
#[inline(always)]
pub fn recv_timeout(&self, duration: Duration) -> Result<T, ErrorTimeout> {
let deadline = SystemTime::now().checked_add(duration).unwrap();
let mut internal = acquire_internal(&self.internal);
if internal.recv_count == 0 {
return Err(ErrorTimeout::Closed);
}
if let Some(v) = internal.queue.pop_front() {
if let Some(mut p) = internal.next_send() {
// if there is a sender take its data and push it in queue
unsafe { internal.queue.push_back(p.recv()) }
}
Ok(v)
} else if let Some(mut p) = internal.next_send() {
drop(internal);
unsafe { Ok(p.recv()) }
} else {
if SystemTime::now() > deadline {
return Err(ErrorTimeout::Timeout);
}
if internal.send_count == 0 {
return Err(ErrorTimeout::SendClosed);
}
// no active waiter so push to queue
let mut ret = MaybeUninit::<T>::uninit();
let mut sig = SyncSignal::new(ret.as_mut_ptr() as *mut T, std::thread::current());
internal.push_recv(sig.as_signal());
drop(internal);
if !sig.wait_timeout(deadline) {
if sig.is_terminated() {
return Err(ErrorTimeout::ReceiveClosed);
}
{
let mut internal = acquire_internal(&self.internal);
if internal.cancel_recv_signal(sig.as_signal()) {
return Err(ErrorTimeout::Timeout);
}
}
// removing receive failed wait for signal response
if !sig.wait() {
return Err(ErrorTimeout::ReceiveClosed);
}
}
Ok(unsafe { ret.assume_init() })
}
// if queue is not empty send data
}
/// Tries receiving from the channel without waiting in the wait list
/// It returns Ok(Some(T)) in case of successful operation and Ok(None) for failed one, or error in case that channel is closed
/// Important note: this function is not lock free as it acquire mutex of channel internal for a short time.
#[inline(always)]
pub fn try_recv(&self) -> Result<Option<T>, Error> {
let mut internal = acquire_internal(&self.internal);
if internal.recv_count == 0 {
return Err(Error::Closed);
}
if let Some(v) = internal.queue.pop_front() {
if let Some(mut p) = internal.next_send() {
// if there is a sender take its data and push it in queue
unsafe { internal.queue.push_back(p.recv()) }
}
return Ok(Some(v));
} else if let Some(mut p) = internal.next_send() {
return unsafe { Ok(Some(p.recv())) };
}
Ok(None)
// if queue is not empty send data
}
/// Returns if the send part of channel is disconnected
pub fn is_disconnected(&mut self) -> bool {
acquire_internal(&self.internal).send_count == 0
}
#[cfg(feature = "async")]
/// Clones receiver as async version of it
pub fn clone_async(&self) -> AsyncReceiver<T> {
let mut internal = acquire_internal(&self.internal);
if internal.recv_count > 0 {
internal.recv_count += 1;
}
AsyncReceiver::<T> {
internal: self.internal.clone(),
}
}
shared_impl!();
}
impl<T> Iterator for Receiver<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
match self.recv() {
Ok(d) => Some(d),
Err(_) => None,
}
}
}
#[cfg(feature = "async")]
impl<T> AsyncReceiver<T> {
// Receives data asynchronously from the channel
#[inline(always)]
pub fn recv(&'_ self) -> ReceiveFuture<'_, T> {
ReceiveFuture {
state: FutureState::Zero,
sig: AsyncSignal::new(),
internal: &self.internal,
data: ManuallyDrop::new(unsafe { std::mem::zeroed() }),
}
}
/// Tries receiving from the channel without waiting in the wait list
/// It returns Ok(Some(T)) in case of successful operation and Ok(None) for failed one, or error in case that channel is closed
/// Important note: this function is not lock free as it acquire mutex of channel internal for a short time.
#[inline(always)]
pub fn try_recv(&self) -> Result<Option<T>, Error> {
let mut internal = acquire_internal(&self.internal);
if internal.recv_count == 0 {
return Err(Error::Closed);
}
if let Some(v) = internal.queue.pop_front() {
if let Some(mut p) = internal.next_send() {
// if there is a sender take its data and push it in queue
unsafe { internal.queue.push_back(p.recv()) }
}
return Ok(Some(v));
} else if let Some(mut p) = internal.next_send() {
return unsafe { Ok(Some(p.recv())) };
}
Ok(None)
// if queue is not empty send data
}
/// Returns sync cloned version of receiver
pub fn clone_sync(&self) -> Receiver<T> {
let mut internal = acquire_internal(&self.internal);
if internal.recv_count > 0 {
internal.recv_count += 1;
}
Receiver::<T> {
internal: self.internal.clone(),
}
}
/// Returns whether send part of channel is closed or not
pub fn is_disconnected(&mut self) -> bool {
acquire_internal(&self.internal).send_count == 0
}
shared_impl!();
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
let mut internal = acquire_internal(&self.internal);
if internal.recv_count > 0 {
internal.recv_count -= 1;
}
}
}
#[cfg(feature = "async")]
impl<T> Drop for AsyncReceiver<T> {
fn drop(&mut self) {
let mut internal = acquire_internal(&self.internal);
if internal.recv_count > 0 {
internal.recv_count -= 1;
}
}
}
impl<T> Clone for Receiver<T> {
fn clone(&self) -> Self {
let mut internal = acquire_internal(&self.internal);
if internal.recv_count > 0 {
internal.recv_count += 1;
}
Self {
internal: self.internal.clone(),
}
}
}
#[cfg(feature = "async")]
impl<T> Clone for AsyncReceiver<T> {
fn clone(&self) -> Self {
let mut internal = acquire_internal(&self.internal);
if internal.recv_count > 0 {
internal.recv_count += 1;
}
Self {
internal: self.internal.clone(),
}
}
}
/// Returns bounded, sync sender and receiver of the channel for type T
/// senders and receivers can produce both async and sync version via clone, clone_sync and clone_async
pub fn bounded<T>(size: usize) -> (Sender<T>, Receiver<T>) {
let internal = ChannelInternal::new(true, size);
(
Sender {
internal: internal.clone(),
},
Receiver { internal },
)
}
/// Returns bounded, async sender and receiver of the channel for type T
/// senders and receivers can produce both async and sync version via clone, clone_sync and clone_async
#[cfg(feature = "async")]
pub fn bounded_async<T>(size: usize) -> (AsyncSender<T>, AsyncReceiver<T>) {
let internal = ChannelInternal::new(true, size);
(
AsyncSender {
internal: internal.clone(),
},
AsyncReceiver { internal },
)
}
const UNBOUNDED_STARTING_SIZE: usize = 2048;
/// Returns unbounded, sync sender and receiver of the channel for type T
/// senders and receivers can produce both async and sync version via clone, clone_sync and clone_async
pub fn unbounded<T>() -> (Sender<T>, Receiver<T>) {
let internal = ChannelInternal::new(false, UNBOUNDED_STARTING_SIZE);
(
Sender {
internal: internal.clone(),
},
Receiver { internal },
)
}
/// Returns unbounded, async sender and receiver of the channel for type T
/// senders and receivers can produce both async and sync version via clone, clone_sync and clone_async
#[cfg(feature = "async")]
pub fn unbounded_async<T>() -> (AsyncSender<T>, AsyncReceiver<T>) {
let internal = ChannelInternal::new(false, UNBOUNDED_STARTING_SIZE);
(
AsyncSender {
internal: internal.clone(),
},
AsyncReceiver { internal },
)
}