@@ -14,7 +14,7 @@ use mio::net::TcpStream as MioTcpStream;
1414
1515use log:: warn;
1616
17- use crate :: utilities:: Timeout ;
17+ use crate :: utilities:: { Timeout , BufferManager } ;
1818use crate :: { TcpConnection , TcpManager , TcpError } ;
1919use crate :: manager:: TcpPollContext ;
2020
@@ -284,26 +284,25 @@ impl TcpStream {
284284 F : Fn ( & [ u8 ] ) -> bool ,
285285 {
286286 let chunk_size = chunk_size. unwrap_or_else ( || NonZeroUsize :: new ( 4096 ) . unwrap ( ) ) ;
287- let maximum_length = maximum_length. map ( |value| NonZeroUsize :: new ( round_up ( value. get ( ) , chunk_size) ) . unwrap ( ) ) ;
288- let mut valid_length = buffer. len ( ) ;
287+ if maximum_length. map_or ( false , |value| value < chunk_size) {
288+ panic ! ( "maximum_length must be greater than or equal to chunk_size!" )
289+ }
290+
291+ let mut buffer = BufferManager :: from ( buffer, maximum_length) ;
289292
290293 loop {
291- adjust_buffer ( buffer , valid_length , chunk_size , maximum_length ) ? ;
292- let done = match self . read_timeout ( & mut buffer [ valid_length.. ] , timeout) {
293- Ok ( 0 ) => Some ( Err ( TcpError :: Incomplete ) ) ,
294+ let spare = buffer . alloc_spare_buffer ( chunk_size ) ;
295+ match self . read_timeout ( spare , timeout) {
296+ Ok ( 0 ) => return Err ( TcpError :: Incomplete ) ,
294297 Ok ( count) => {
295- valid_length += count;
296- match fn_complete ( & buffer[ ..valid_length ] ) {
297- true => Some ( Ok ( ( ) ) ) ,
298- false => None ,
298+ buffer . commit ( count) . map_err ( |_err| TcpError :: TooBig ) ? ;
299+ match fn_complete ( buffer. valid_data ( ) ) {
300+ true => return Ok ( ( ) ) ,
301+ false => { } ,
299302 }
300303 } ,
301- Err ( error) => Some ( Err ( error) ) ,
304+ Err ( error) => return Err ( error) ,
302305 } ;
303- if let Some ( result) = done {
304- buffer. truncate ( valid_length) ;
305- return result;
306- }
307306 }
308307 }
309308
@@ -445,25 +444,3 @@ fn into_io_result<T>(result: Result<T, TcpError>) -> IoResult<T> {
445444 Err ( error) => Err ( error. into ( ) ) ,
446445 }
447446}
448-
449- fn adjust_buffer ( buffer : & mut Vec < u8 > , length : usize , chunk_size : NonZeroUsize , maximum_length : Option < NonZeroUsize > ) -> Result < ( ) , TcpError > {
450- let mut capacity = round_up ( length, chunk_size) ;
451- while capacity <= length {
452- capacity = capacity. checked_add ( chunk_size. get ( ) ) . expect ( "Numerical overflow!" )
453- }
454- if capacity > buffer. len ( ) {
455- if maximum_length. map_or ( false , |max_len| capacity > max_len. get ( ) ) {
456- return Err ( TcpError :: TooBig ) ;
457- }
458- buffer. resize ( capacity, 0 ) ;
459- }
460- Ok ( ( ) )
461- }
462-
463- fn round_up ( value : usize , block_size : NonZeroUsize ) -> usize {
464- let block_size = block_size. get ( ) ;
465- match value % block_size {
466- 0 => value,
467- r => value. checked_add ( block_size - r) . expect ( "Numerical overflow!" ) ,
468- }
469- }
0 commit comments