@@ -10,46 +10,40 @@ pin_project_lite::pin_project! {
10
10
/// An SSE protocol encoder.
11
11
#[ derive( Debug ) ]
12
12
pub struct Encoder {
13
- buf: Option <Vec <u8 >>,
13
+ buf: Box <[ u8 ] >,
14
+ cursor: usize ,
14
15
#[ pin]
15
16
receiver: async_channel:: Receiver <Vec <u8 >>,
16
- cursor: usize ,
17
17
}
18
18
}
19
19
20
20
impl AsyncRead for Encoder {
21
21
fn poll_read (
22
- mut self : Pin < & mut Self > ,
22
+ self : Pin < & mut Self > ,
23
23
cx : & mut Context < ' _ > ,
24
24
buf : & mut [ u8 ] ,
25
25
) -> Poll < io:: Result < usize > > {
26
- // Request a new buffer if we don't have one yet.
27
- if let None = self . buf {
28
- self . buf = match ready ! ( Pin :: new( & mut self . receiver) . poll_next( cx) ) {
26
+ let mut this = self . project ( ) ;
27
+ // Request a new buffer if current one is exhausted.
28
+ if this. buf . len ( ) <= * this. cursor {
29
+ match ready ! ( this. receiver. as_mut( ) . poll_next( cx) ) {
29
30
Some ( buf) => {
30
31
log:: trace!( "> Received a new buffer with len {}" , buf. len( ) ) ;
31
- Some ( buf)
32
+ * this. buf = buf. into_boxed_slice ( ) ;
33
+ * this. cursor = 0 ;
32
34
}
33
35
None => {
34
36
log:: trace!( "> Encoder done reading" ) ;
35
37
return Poll :: Ready ( Ok ( 0 ) ) ;
36
38
}
37
39
} ;
38
- } ;
40
+ }
39
41
40
42
// Write the current buffer to completion.
41
- let local_buf = self . buf . as_mut ( ) . unwrap ( ) ;
42
- let local_len = local_buf. len ( ) ;
43
+ let local_buf = & this. buf [ * this. cursor ..] ;
43
44
let max = buf. len ( ) . min ( local_buf. len ( ) ) ;
44
45
buf[ ..max] . clone_from_slice ( & local_buf[ ..max] ) ;
45
-
46
- self . cursor += max;
47
-
48
- // Reset values if we're done reading.
49
- if self . cursor == local_len {
50
- self . buf = None ;
51
- self . cursor = 0 ;
52
- } ;
46
+ * this. cursor += max;
53
47
54
48
// Return bytes read.
55
49
Poll :: Ready ( Ok ( max) )
@@ -86,7 +80,7 @@ pub fn encode() -> (Sender, Encoder) {
86
80
let ( sender, receiver) = async_channel:: bounded ( 1 ) ;
87
81
let encoder = Encoder {
88
82
receiver,
89
- buf : None ,
83
+ buf : Box :: default ( ) ,
90
84
cursor : 0 ,
91
85
} ;
92
86
( Sender ( sender) , encoder)
0 commit comments