@@ -187,6 +187,32 @@ pub trait Read {
187
187
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
188
188
fn read ( & mut self , buf : & mut [ u8 ] ) -> Result < usize > ;
189
189
190
+ /// Read as many bytes as buf can hold, stopping at EOF or on error
191
+ ///
192
+ /// This method will continuously call `read` while there is more data to
193
+ /// read. This method will not return until the entire buffer has been
194
+ /// successfully read or an error occurs. The first error generated from
195
+ /// this method will be returned.
196
+ ///
197
+ /// # Errors
198
+ ///
199
+ /// This function will return the first error that `read` returns.
200
+ #[ stable( feature = "rust1" , since = "1.0.0" ) ]
201
+ fn read_all ( & mut self , mut buf : & mut [ u8 ] ) -> Result < ( ) > {
202
+ let mut total = 0 ;
203
+ while total < buf. len ( ) {
204
+ match self . read ( & mut buf[ total..] ) {
205
+ Ok ( 0 ) => return Err ( Error :: new ( ErrorKind :: ShortRead ( total) ,
206
+ "failed to read whole buffer" ,
207
+ None ) ) ,
208
+ Ok ( n) => total += n,
209
+ Err ( ref e) if e. kind ( ) == ErrorKind :: Interrupted => { }
210
+ Err ( e) => return Err ( e) ,
211
+ }
212
+ }
213
+ Ok ( ( ) )
214
+ }
215
+
190
216
/// Read all bytes until EOF in this source, placing them into `buf`.
191
217
///
192
218
/// All bytes read from this source will be appended to the specified buffer
@@ -989,6 +1015,21 @@ mod tests {
989
1015
assert_eq ! ( s. next( ) , None ) ;
990
1016
}
991
1017
1018
+ #[ test]
1019
+ fn read_all ( ) {
1020
+ let mut c = Cursor :: new ( b"hello" ) ;
1021
+ let mut v = [ 0 as u8 ; 5 ] ;
1022
+ assert_eq ! ( c. read_all( & mut v) , Ok ( ) ) ;
1023
+ assert_eq ! ( v, b"hello" ) ;
1024
+
1025
+ let mut c = Cursor :: new ( b"short" ) ;
1026
+ let mut v = [ 115 as u8 ; 6 ] ;
1027
+ assert_eq ! ( c. read_all( & mut v) , Error :: new( ErrorKind :: ShortRead ( 5 ) ,
1028
+ "failed to read whole buffer" ,
1029
+ None ) ) ;
1030
+ assert_eq ! ( v, b"shorts" ) ;
1031
+ }
1032
+
992
1033
#[ test]
993
1034
fn read_to_end ( ) {
994
1035
let mut c = Cursor :: new ( & b"" [ ..] ) ;
0 commit comments