1
1
use std:: {
2
+ collections:: VecDeque ,
2
3
io:: { BufWriter , Write } ,
3
4
thread:: sleep,
4
5
time:: Duration ,
@@ -28,6 +29,7 @@ pub struct CommandResponse {
28
29
pub struct Connection {
29
30
serial : Box < dyn SerialPort > ,
30
31
decoder : SlipDecoder ,
32
+ buffer : VecDeque < u8 > ,
31
33
}
32
34
33
35
#[ derive( Zeroable , Pod , Copy , Clone , Debug ) ]
@@ -44,6 +46,7 @@ impl Connection {
44
46
Connection {
45
47
serial,
46
48
decoder : SlipDecoder :: new ( ) ,
49
+ buffer : VecDeque :: with_capacity ( 128 ) ,
47
50
}
48
51
}
49
52
@@ -105,18 +108,19 @@ impl Connection {
105
108
}
106
109
107
110
pub fn read_response ( & mut self ) -> Result < Option < CommandResponse > , Error > {
108
- let response = self . read ( ) ?;
109
- if response. len ( ) < 10 {
110
- return Ok ( None ) ;
111
+ match self . read ( 10 ) ? {
112
+ None => Ok ( None ) ,
113
+ Some ( response) => {
114
+ let mut cursor = Cursor :: new ( response) ;
115
+ let header = cursor. read_le ( ) ?;
116
+ Ok ( Some ( header) )
117
+ }
111
118
}
112
-
113
- let mut cursor = Cursor :: new ( response) ;
114
- let header = cursor. read_le ( ) ?;
115
-
116
- Ok ( Some ( header) )
117
119
}
118
120
119
121
pub fn write_command ( & mut self , command : Command ) -> Result < ( ) , Error > {
122
+ self . buffer . clear ( ) ;
123
+ self . serial . clear ( serialport:: ClearBuffer :: Input ) ?;
120
124
let mut writer = BufWriter :: new ( & mut self . serial ) ;
121
125
let mut encoder = SlipEncoder :: new ( & mut writer) ?;
122
126
command. write ( & mut encoder) ?;
@@ -167,13 +171,24 @@ impl Connection {
167
171
Ok ( ( ) )
168
172
}
169
173
170
- fn read ( & mut self ) -> Result < Vec < u8 > , Error > {
174
+ fn read ( & mut self , len : usize ) -> Result < Option < Vec < u8 > > , Error > {
171
175
let mut output = Vec :: with_capacity ( 1024 ) ;
172
176
self . decoder . decode ( & mut self . serial , & mut output) ?;
173
- Ok ( output)
177
+
178
+ self . buffer . extend ( & output) ;
179
+ if self . buffer . len ( ) < len {
180
+ return Ok ( None ) ;
181
+ }
182
+
183
+ // reuse allocation
184
+ output. clear ( ) ;
185
+ output. extend ( self . buffer . drain ( ..) ) ;
186
+
187
+ Ok ( Some ( output) )
174
188
}
175
189
176
190
pub fn flush ( & mut self ) -> Result < ( ) , Error > {
191
+ self . buffer . clear ( ) ;
177
192
self . serial . flush ( ) ?;
178
193
Ok ( ( ) )
179
194
}
0 commit comments