@@ -2,7 +2,7 @@ use async_std::net::UdpSocket;
2
2
use async_std:: stream:: { Stream , StreamExt } ;
3
3
use async_std:: task;
4
4
use futures:: future:: Future ;
5
- use futures:: pin_mut;
5
+ use futures:: { pin_mut, ready } ;
6
6
use std:: io:: Result ;
7
7
use std:: net:: SocketAddr ;
8
8
use std:: pin:: Pin ;
@@ -54,37 +54,56 @@ async fn send_loop(bind_addr: &str, peer_addr: &str) -> Result<()> {
54
54
}
55
55
}
56
56
57
+ type ReceiveResult = Result < ( usize , SocketAddr ) > ;
58
+
57
59
struct UdpStream {
58
- socket : UdpSocket ,
59
- buf : Vec < u8 > ,
60
+ inner : Option < ( UdpSocket , Vec < u8 > ) > ,
61
+ fut : Option < Pin < Box < dyn Future < Output = ( UdpSocket , Vec < u8 > , ReceiveResult ) > + Send + Sync > > > ,
60
62
}
61
63
62
64
impl UdpStream {
63
65
pub fn new ( socket : UdpSocket ) -> Self {
66
+ let buf = vec ! [ 0u8 ; 1024 ] ;
64
67
Self {
65
- socket ,
66
- buf : vec ! [ 0u8 ; 1024 ] ,
68
+ fut : None ,
69
+ inner : Some ( ( socket , buf ) ) ,
67
70
}
68
71
}
69
72
}
70
-
71
73
impl Stream for UdpStream {
72
74
type Item = Result < ( Vec < u8 > , SocketAddr ) > ;
73
- fn poll_next ( self : Pin < & mut Self > , cx : & mut Context < ' _ > ) -> Poll < Option < Self :: Item > > {
74
- let this = self . get_mut ( ) ;
75
- let res = {
76
- let fut = this. socket . recv_from ( & mut this. buf ) ;
77
- pin_mut ! ( fut) ;
78
- fut. poll ( cx)
75
+ fn poll_next ( mut self : Pin < & mut Self > , cx : & mut Context < ' _ > ) -> Poll < Option < Self :: Item > > {
76
+ let mut fut = if let Some ( fut) = self . fut . take ( ) {
77
+ fut
78
+ } else {
79
+ if let Some ( ( socket, buf) ) = self . inner . take ( ) {
80
+ let fut = recv_next ( socket, buf) ;
81
+ Box :: pin ( fut)
82
+ } else {
83
+ unreachable ! ( )
84
+ }
79
85
} ;
86
+
87
+ let res = Pin :: new ( & mut fut) . poll ( cx) ;
88
+
80
89
match res {
81
- Poll :: Pending => Poll :: Pending ,
82
- Poll :: Ready ( Ok ( res) ) => {
83
- let buf = this. buf [ ..res. 0 ] . to_vec ( ) ;
84
- let peer = res. 1 ;
85
- Poll :: Ready ( Some ( Ok ( ( buf, peer) ) ) )
90
+ Poll :: Pending => {
91
+ self . fut = Some ( fut) ;
92
+ Poll :: Pending
86
93
}
87
- Poll :: Ready ( Err ( e) ) => Poll :: Ready ( Some ( Err ( e) ) ) ,
94
+ Poll :: Ready ( ( socket, buf, res) ) => match res {
95
+ Ok ( ( n, peer_addr) ) => {
96
+ let vec = buf[ ..n] . to_vec ( ) ;
97
+ self . inner = Some ( ( socket, buf) ) ;
98
+ Poll :: Ready ( Some ( Ok ( ( vec, peer_addr) ) ) )
99
+ }
100
+ Err ( e) => Poll :: Ready ( Some ( Err ( e) ) ) ,
101
+ } ,
88
102
}
89
103
}
90
104
}
105
+
106
+ async fn recv_next ( socket : UdpSocket , mut buf : Vec < u8 > ) -> ( UdpSocket , Vec < u8 > , ReceiveResult ) {
107
+ let res = socket. recv_from ( & mut buf) . await ;
108
+ ( socket, buf, res)
109
+ }
0 commit comments