@@ -303,6 +303,44 @@ extension_trait! {
303
303
{
304
304
take:: Take { inner: self , limit }
305
305
}
306
+
307
+ #[ doc = r#"
308
+ Creates a "by reference" adaptor for this instance of `Read`.
309
+
310
+ The returned adaptor also implements `Read` and will simply borrow this
311
+ current reader.
312
+
313
+ # Examples
314
+
315
+ [`File`][file]s implement `Read`:
316
+
317
+ [file]: ../fs/struct.File.html
318
+
319
+ ```no_run
320
+ use async_std::io;
321
+ use async_std::prelude::*;
322
+ use async_std::fs::File;
323
+
324
+ fn main() -> io::Result<()> { async_std::task::block_on(async {
325
+ let mut f = File::open("foo.txt").await?;
326
+ let mut buffer = Vec::new();
327
+ let mut other_buffer = Vec::new();
328
+
329
+ {
330
+ let reference = f.by_ref();
331
+
332
+ // read at most 5 bytes
333
+ reference.take(5).read_to_end(&mut buffer).await?;
334
+
335
+ } // drop our &mut reference so we can use f again
336
+
337
+ // original file still usable, read the rest
338
+ f.read_to_end(&mut other_buffer).await?;
339
+ Ok(())
340
+ }) }
341
+ ```
342
+ "# ]
343
+ fn by_ref( & mut self ) -> & mut Self where Self : Sized { self }
306
344
}
307
345
308
346
impl <T : Read + Unpin + ?Sized > Read for Box <T > {
@@ -349,3 +387,31 @@ extension_trait! {
349
387
}
350
388
}
351
389
}
390
+
391
+ #[ cfg( test) ]
392
+ mod tests {
393
+ use crate :: io;
394
+ use crate :: prelude:: * ;
395
+
396
+ #[ test]
397
+ fn test_read_by_ref ( ) -> io:: Result < ( ) > {
398
+ crate :: task:: block_on ( async {
399
+ let mut f = io:: Cursor :: new ( vec ! [ 0u8 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] ) ;
400
+ let mut buffer = Vec :: new ( ) ;
401
+ let mut other_buffer = Vec :: new ( ) ;
402
+
403
+ {
404
+ let reference = f. by_ref ( ) ;
405
+
406
+ // read at most 5 bytes
407
+ assert_eq ! ( reference. take( 5 ) . read_to_end( & mut buffer) . await ?, 5 ) ;
408
+ assert_eq ! ( & buffer, & [ 0 , 1 , 2 , 3 , 4 ] )
409
+ } // drop our &mut reference so we can use f again
410
+
411
+ // original file still usable, read the rest
412
+ assert_eq ! ( f. read_to_end( & mut other_buffer) . await ?, 4 ) ;
413
+ assert_eq ! ( & other_buffer, & [ 5 , 6 , 7 , 8 ] ) ;
414
+ Ok ( ( ) )
415
+ } )
416
+ }
417
+ }
0 commit comments