1
1
use std:: cell:: UnsafeCell ;
2
- use std:: fmt;
2
+ use std:: error:: Error ;
3
+ use std:: fmt:: { self , Debug , Display } ;
3
4
use std:: future:: Future ;
4
5
use std:: isize;
5
6
use std:: marker:: PhantomData ;
@@ -31,6 +32,7 @@ use crate::sync::WakerSet;
31
32
/// # Examples
32
33
///
33
34
/// ```
35
+ /// # fn main() -> Result<(), async_std::sync::RecvError> {
34
36
/// # async_std::task::block_on(async {
35
37
/// #
36
38
/// use std::time::Duration;
@@ -50,10 +52,11 @@ use crate::sync::WakerSet;
50
52
/// });
51
53
///
52
54
/// task::sleep(Duration::from_secs(1)).await;
53
- /// assert_eq!(r.recv().await, Some(1));
54
- /// assert_eq!(r.recv().await, Some(2));
55
+ /// assert_eq!(r.recv().await?, 1);
56
+ /// assert_eq!(r.recv().await?, 2);
57
+ /// # Ok(())
55
58
/// #
56
- /// # })
59
+ /// # }) }
57
60
/// ```
58
61
#[ cfg( feature = "unstable" ) ]
59
62
#[ cfg_attr( feature = "docs" , doc( cfg( unstable) ) ) ]
@@ -112,6 +115,7 @@ impl<T> Sender<T> {
112
115
/// # Examples
113
116
///
114
117
/// ```
118
+ /// # fn main() -> Result<(), async_std::sync::RecvError> {
115
119
/// # async_std::task::block_on(async {
116
120
/// #
117
121
/// use async_std::sync::channel;
@@ -124,11 +128,12 @@ impl<T> Sender<T> {
124
128
/// s.send(2).await;
125
129
/// });
126
130
///
127
- /// assert_eq!(r.recv().await, Some(1) );
128
- /// assert_eq!(r.recv().await, Some(2) );
129
- /// assert_eq !(r.recv().await, None );
131
+ /// assert_eq!(r.recv().await?, 1 );
132
+ /// assert_eq!(r.recv().await?, 2 );
133
+ /// assert !(r.recv().await.is_err() );
130
134
/// #
131
- /// # })
135
+ /// # Ok(())
136
+ /// # }) }
132
137
/// ```
133
138
pub async fn send ( & self , msg : T ) {
134
139
struct SendFuture < ' a , T > {
@@ -192,6 +197,27 @@ impl<T> Sender<T> {
192
197
. await
193
198
}
194
199
200
+ /// Attempts to send a message into the channel.
201
+ ///
202
+ /// If the channel is full, this method will return an error.
203
+ ///
204
+ /// # Examples
205
+ ///
206
+ /// ```
207
+ /// # async_std::task::block_on(async {
208
+ /// #
209
+ /// use async_std::sync::channel;
210
+ ///
211
+ /// let (s, r) = channel(1);
212
+ /// assert!(s.try_send(1).is_ok());
213
+ /// assert!(s.try_send(2).is_err());
214
+ /// #
215
+ /// # })
216
+ /// ```
217
+ pub fn try_send ( & self , msg : T ) -> Result < ( ) , TrySendError < T > > {
218
+ self . channel . try_send ( msg)
219
+ }
220
+
195
221
/// Returns the channel capacity.
196
222
///
197
223
/// # Examples
@@ -313,6 +339,7 @@ impl<T> fmt::Debug for Sender<T> {
313
339
/// # Examples
314
340
///
315
341
/// ```
342
+ /// # fn main() -> Result<(), async_std::sync::RecvError> {
316
343
/// # async_std::task::block_on(async {
317
344
/// #
318
345
/// use std::time::Duration;
@@ -328,10 +355,11 @@ impl<T> fmt::Debug for Sender<T> {
328
355
/// s.send(2).await;
329
356
/// });
330
357
///
331
- /// assert_eq!(r.recv().await, Some(1) ); // Received immediately.
332
- /// assert_eq!(r.recv().await, Some(2) ); // Received after 1 second.
358
+ /// assert_eq!(r.recv().await?, 1 ); // Received immediately.
359
+ /// assert_eq!(r.recv().await?, 2 ); // Received after 1 second.
333
360
/// #
334
- /// # })
361
+ /// # Ok(())
362
+ /// # }) }
335
363
/// ```
336
364
#[ cfg( feature = "unstable" ) ]
337
365
#[ cfg_attr( feature = "docs" , doc( cfg( unstable) ) ) ]
@@ -353,6 +381,7 @@ impl<T> Receiver<T> {
353
381
/// # Examples
354
382
///
355
383
/// ```
384
+ /// # fn main() -> Result<(), async_std::sync::RecvError> {
356
385
/// # async_std::task::block_on(async {
357
386
/// #
358
387
/// use async_std::sync::channel;
@@ -366,22 +395,21 @@ impl<T> Receiver<T> {
366
395
/// // Then we drop the sender
367
396
/// });
368
397
///
369
- /// assert_eq!(r.recv().await, Some(1));
370
- /// assert_eq!(r.recv().await, Some(2));
371
- ///
372
- /// // recv() returns `None`
373
- /// assert_eq!(r.recv().await, None);
398
+ /// assert_eq!(r.recv().await?, 1);
399
+ /// assert_eq!(r.recv().await?, 2);
400
+ /// assert!(r.recv().await.is_err());
374
401
/// #
375
- /// # })
402
+ /// # Ok(())
403
+ /// # }) }
376
404
/// ```
377
- pub async fn recv ( & self ) -> Option < T > {
405
+ pub async fn recv ( & self ) -> Result < T , RecvError > {
378
406
struct RecvFuture < ' a , T > {
379
407
channel : & ' a Channel < T > ,
380
408
opt_key : Option < usize > ,
381
409
}
382
410
383
411
impl < T > Future for RecvFuture < ' _ , T > {
384
- type Output = Option < T > ;
412
+ type Output = Result < T , RecvError > ;
385
413
386
414
fn poll ( mut self : Pin < & mut Self > , cx : & mut Context < ' _ > ) -> Poll < Self :: Output > {
387
415
poll_recv (
@@ -409,6 +437,30 @@ impl<T> Receiver<T> {
409
437
. await
410
438
}
411
439
440
+ /// Attempts to receive a message from the channel.
441
+ ///
442
+ /// If the channel is empty, this method will return an error.
443
+ ///
444
+ /// # Examples
445
+ ///
446
+ /// ```
447
+ /// # async_std::task::block_on(async {
448
+ /// #
449
+ /// use async_std::sync::channel;
450
+ ///
451
+ /// let (s, r) = channel(1);
452
+ ///
453
+ /// s.send(1u8).await;
454
+ ///
455
+ /// assert!(r.try_recv().is_ok());
456
+ /// assert!(r.try_recv().is_err());
457
+ /// #
458
+ /// # })
459
+ /// ```
460
+ pub fn try_recv ( & self ) -> Result < T , TryRecvError > {
461
+ self . channel . try_recv ( )
462
+ }
463
+
412
464
/// Returns the channel capacity.
413
465
///
414
466
/// # Examples
@@ -523,12 +575,13 @@ impl<T> Stream for Receiver<T> {
523
575
524
576
fn poll_next ( mut self : Pin < & mut Self > , cx : & mut Context < ' _ > ) -> Poll < Option < Self :: Item > > {
525
577
let this = & mut * self ;
526
- poll_recv (
578
+ let res = futures_core :: ready! ( poll_recv(
527
579
& this. channel,
528
580
& this. channel. stream_wakers,
529
581
& mut this. opt_key,
530
582
cx,
531
- )
583
+ ) ) ;
584
+ Poll :: Ready ( res. ok ( ) )
532
585
}
533
586
}
534
587
@@ -547,7 +600,7 @@ fn poll_recv<T>(
547
600
wakers : & WakerSet ,
548
601
opt_key : & mut Option < usize > ,
549
602
cx : & mut Context < ' _ > ,
550
- ) -> Poll < Option < T > > {
603
+ ) -> Poll < Result < T , RecvError > > {
551
604
loop {
552
605
// If the current task is in the set, remove it.
553
606
if let Some ( key) = opt_key. take ( ) {
@@ -556,8 +609,8 @@ fn poll_recv<T>(
556
609
557
610
// Try receiving a message.
558
611
match channel. try_recv ( ) {
559
- Ok ( msg) => return Poll :: Ready ( Some ( msg) ) ,
560
- Err ( TryRecvError :: Disconnected ) => return Poll :: Ready ( None ) ,
612
+ Ok ( msg) => return Poll :: Ready ( Ok ( msg) ) ,
613
+ Err ( TryRecvError :: Disconnected ) => return Poll :: Ready ( Err ( RecvError { } ) ) ,
561
614
Err ( TryRecvError :: Empty ) => {
562
615
// Insert this receive operation.
563
616
* opt_key = Some ( wakers. insert ( cx) ) ;
@@ -936,20 +989,70 @@ impl<T> Drop for Channel<T> {
936
989
}
937
990
}
938
991
939
- /// An error returned from the `try_send()` method.
940
- enum TrySendError < T > {
992
+ /// An error returned from the `try_send` method.
993
+ #[ cfg( feature = "unstable" ) ]
994
+ #[ cfg_attr( feature = "docs" , doc( cfg( unstable) ) ) ]
995
+ pub enum TrySendError < T > {
941
996
/// The channel is full but not disconnected.
942
997
Full ( T ) ,
943
998
944
999
/// The channel is full and disconnected.
945
1000
Disconnected ( T ) ,
946
1001
}
947
1002
948
- /// An error returned from the `try_recv()` method.
949
- enum TryRecvError {
1003
+ impl < T > Error for TrySendError < T > { }
1004
+
1005
+ impl < T > Debug for TrySendError < T > {
1006
+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
1007
+ match self {
1008
+ Self :: Full ( _) => Debug :: fmt ( "Full<T>" , f) ,
1009
+ Self :: Disconnected ( _) => Debug :: fmt ( "Disconnected<T>" , f) ,
1010
+ }
1011
+ }
1012
+ }
1013
+
1014
+ impl < T > Display for TrySendError < T > {
1015
+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
1016
+ match self {
1017
+ Self :: Full ( _) => Display :: fmt ( "The channel is full." , f) ,
1018
+ Self :: Disconnected ( _) => Display :: fmt ( "The channel is full and disconnected." , f) ,
1019
+ }
1020
+ }
1021
+ }
1022
+
1023
+ /// An error returned from the `try_recv` method.
1024
+ #[ cfg( feature = "unstable" ) ]
1025
+ #[ cfg_attr( feature = "docs" , doc( cfg( unstable) ) ) ]
1026
+ #[ derive( Debug ) ]
1027
+ pub enum TryRecvError {
950
1028
/// The channel is empty but not disconnected.
951
1029
Empty ,
952
1030
953
1031
/// The channel is empty and disconnected.
954
1032
Disconnected ,
955
1033
}
1034
+
1035
+ impl Error for TryRecvError { }
1036
+
1037
+ impl Display for TryRecvError {
1038
+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
1039
+ match self {
1040
+ Self :: Empty => Display :: fmt ( "The channel is empty." , f) ,
1041
+ Self :: Disconnected => Display :: fmt ( "The channel is empty and disconnected." , f) ,
1042
+ }
1043
+ }
1044
+ }
1045
+
1046
+ /// An error returned from the `recv` method.
1047
+ #[ cfg( feature = "unstable" ) ]
1048
+ #[ cfg_attr( feature = "docs" , doc( cfg( unstable) ) ) ]
1049
+ #[ derive( Debug ) ]
1050
+ pub struct RecvError ;
1051
+
1052
+ impl Error for RecvError { }
1053
+
1054
+ impl Display for RecvError {
1055
+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
1056
+ Display :: fmt ( "The channel is empty." , f)
1057
+ }
1058
+ }
0 commit comments