Skip to content

Commit ff664f3

Browse files
committed
More docs for std::io::Read
1 parent 2074b19 commit ff664f3

File tree

1 file changed

+278
-12
lines changed

1 file changed

+278
-12
lines changed

src/libstd/io/mod.rs

Lines changed: 278 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -127,14 +127,49 @@ fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize>
127127
ret
128128
}
129129

130-
/// A trait for objects which are byte-oriented sources.
130+
/// The `Read` trait allows for reading bytes from a source.
131131
///
132-
/// Readers are defined by one method, `read`. Each call to `read` will attempt
133-
/// to pull bytes from this source into a provided buffer.
132+
/// Implementors of the `Read` trait are sometimes called 'readers'.
134133
///
135-
/// Readers are intended to be composable with one another. Many objects
136-
/// throughout the I/O and related libraries take and provide types which
137-
/// implement the `Read` trait.
134+
/// Readers are defined by one required method, `read()`. Each call to `read`
135+
/// will attempt to pull bytes from this source into a provided buffer. A
136+
/// number of other methods are implemented in terms of `read()`, giving
137+
/// implementors a number of ways to read bytes while only needing to implement
138+
/// a single method.
139+
///
140+
/// Readers are intended to be composable with one another. Many implementors
141+
/// throughout `std::io` take and provide types which implement the `Read`
142+
/// trait.
143+
///
144+
/// # Examples
145+
///
146+
/// [`File`][file]s implement `Read`:
147+
///
148+
/// [file]: ../std/fs/struct.File.html
149+
///
150+
/// ```
151+
/// use std::io;
152+
/// use std::fs::File;
153+
/// use std::io::Read;
154+
///
155+
/// # fn foo() -> io::Result<()> {
156+
/// let mut f = try!(File::open("foo.txt"));
157+
/// let mut buffer = Vec::new();
158+
///
159+
/// // read some bytes
160+
/// f.read(&mut buffer).unwrap();
161+
///
162+
/// // read the whole file
163+
/// f.read_to_end(&mut buffer).unwrap();
164+
///
165+
/// // read into a String, so that you don't need to do the conversion.
166+
/// let mut buffer = String::new();
167+
/// f.read_to_string(&mut buffer).unwrap();
168+
///
169+
/// // and more! See the other methods for more details.
170+
/// # Ok(())
171+
/// # }
172+
/// ```
138173
#[stable(feature = "rust1", since = "1.0.0")]
139174
pub trait Read {
140175
/// Pull some bytes from this source into the specified buffer, returning
@@ -164,6 +199,27 @@ pub trait Read {
164199
/// If this function encounters any form of I/O or other error, an error
165200
/// variant will be returned. If an error is returned then it must be
166201
/// guaranteed that no bytes were read.
202+
///
203+
/// # Examples
204+
///
205+
/// [`File`][file]s implement `Read`:
206+
///
207+
/// [file]: ../std/fs/struct.File.html
208+
///
209+
/// ```
210+
/// use std::io;
211+
/// use std::io::prelude::*;
212+
/// use std::fs::File;
213+
///
214+
/// # fn foo() -> io::Result<()> {
215+
/// let mut f = try!(File::open("foo.txt"));
216+
/// let mut buffer = [0; 10];
217+
///
218+
/// // read 10 bytes
219+
/// try!(f.read(&mut buffer[..]));
220+
/// # Ok(())
221+
/// # }
222+
/// ```
167223
#[stable(feature = "rust1", since = "1.0.0")]
168224
fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
169225

@@ -185,6 +241,27 @@ pub trait Read {
185241
/// If any other read error is encountered then this function immediately
186242
/// returns. Any bytes which have already been read will be appended to
187243
/// `buf`.
244+
///
245+
/// # Examples
246+
///
247+
/// [`File`][file]s implement `Read`:
248+
///
249+
/// [file]: ../std/fs/struct.File.html
250+
///
251+
/// ```
252+
/// use std::io;
253+
/// use std::io::prelude::*;
254+
/// use std::fs::File;
255+
///
256+
/// # fn foo() -> io::Result<()> {
257+
/// let mut f = try!(File::open("foo.txt"));
258+
/// let mut buffer = Vec::new();
259+
///
260+
/// // read the whole file
261+
/// try!(f.read_to_end(&mut buffer));
262+
/// # Ok(())
263+
/// # }
264+
/// ```
188265
#[stable(feature = "rust1", since = "1.0.0")]
189266
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
190267
read_to_end(self, buf)
@@ -200,7 +277,29 @@ pub trait Read {
200277
/// If the data in this stream is *not* valid UTF-8 then an error is
201278
/// returned and `buf` is unchanged.
202279
///
203-
/// See `read_to_end` for other error semantics.
280+
/// See [`read_to_end()`][readtoend] for other error semantics.
281+
///
282+
/// [readtoend]: #method.read_to_end
283+
///
284+
/// # Examples
285+
///
286+
/// [`File`][file]s implement `Read`:
287+
///
288+
/// [file]: ../std/fs/struct.File.html
289+
///
290+
/// ```
291+
/// use std::io;
292+
/// use std::io::prelude::*;
293+
/// use std::fs::File;
294+
///
295+
/// # fn foo() -> io::Result<()> {
296+
/// let mut f = try!(File::open("foo.txt"));
297+
/// let mut buffer = String::new();
298+
///
299+
/// try!(f.read_to_string(&mut buffer));
300+
/// # Ok(())
301+
/// # }
302+
/// ```
204303
#[stable(feature = "rust1", since = "1.0.0")]
205304
fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
206305
// Note that we do *not* call `.read_to_end()` here. We are passing
@@ -219,6 +318,36 @@ pub trait Read {
219318
///
220319
/// The returned adaptor also implements `Read` and will simply borrow this
221320
/// current reader.
321+
///
322+
/// # Examples
323+
///
324+
/// [`File`][file]s implement `Read`:
325+
///
326+
/// [file]: ../std/fs/struct.File.html
327+
///
328+
/// ```
329+
/// use std::io;
330+
/// use std::io::Read;
331+
/// use std::fs::File;
332+
///
333+
/// # fn foo() -> io::Result<()> {
334+
/// let mut f = try!(File::open("foo.txt"));
335+
/// let mut buffer = Vec::new();
336+
/// let mut other_buffer = Vec::new();
337+
///
338+
/// {
339+
/// let reference = f.by_ref();
340+
///
341+
/// // read at most 5 bytes
342+
/// try!(reference.take(5).read_to_end(&mut buffer));
343+
///
344+
/// } // drop our &mut reference so we can use f again
345+
///
346+
/// // original file still usable, read the rest
347+
/// try!(f.read_to_end(&mut other_buffer));
348+
/// # Ok(())
349+
/// # }
350+
/// ```
222351
#[stable(feature = "rust1", since = "1.0.0")]
223352
fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
224353

@@ -228,6 +357,27 @@ pub trait Read {
228357
/// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
229358
/// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
230359
/// this iterator.
360+
///
361+
/// # Examples
362+
///
363+
/// [`File`][file]s implement `Read`:
364+
///
365+
/// [file]: ../std/fs/struct.File.html
366+
///
367+
/// ```
368+
/// use std::io;
369+
/// use std::io::prelude::*;
370+
/// use std::fs::File;
371+
///
372+
/// # fn foo() -> io::Result<()> {
373+
/// let mut f = try!(File::open("foo.txt"));
374+
///
375+
/// for byte in f.bytes() {
376+
/// println!("{}", byte.unwrap());
377+
/// }
378+
/// # Ok(())
379+
/// # }
380+
/// ```
231381
#[stable(feature = "rust1", since = "1.0.0")]
232382
fn bytes(self) -> Bytes<Self> where Self: Sized {
233383
Bytes { inner: self }
@@ -243,6 +393,28 @@ pub trait Read {
243393
///
244394
/// Currently this adaptor will discard intermediate data read, and should
245395
/// be avoided if this is not desired.
396+
///
397+
/// # Examples
398+
///
399+
/// [`File`][file]s implement `Read`:
400+
///
401+
/// [file]: ../std/fs/struct.File.html
402+
///
403+
/// ```
404+
/// #![feature(io)]
405+
/// use std::io;
406+
/// use std::io::prelude::*;
407+
/// use std::fs::File;
408+
///
409+
/// # fn foo() -> io::Result<()> {
410+
/// let mut f = try!(File::open("foo.txt"));
411+
///
412+
/// for c in f.chars() {
413+
/// println!("{}", c.unwrap());
414+
/// }
415+
/// # Ok(())
416+
/// # }
417+
/// ```
246418
#[unstable(feature = "io", reason = "the semantics of a partial read/write \
247419
of where errors happen is currently \
248420
unclear and may change")]
@@ -255,6 +427,31 @@ pub trait Read {
255427
/// The returned `Read` instance will first read all bytes from this object
256428
/// until EOF is encountered. Afterwards the output is equivalent to the
257429
/// output of `next`.
430+
///
431+
/// # Examples
432+
///
433+
/// [`File`][file]s implement `Read`:
434+
///
435+
/// [file]: ../std/fs/struct.File.html
436+
///
437+
/// ```
438+
/// use std::io;
439+
/// use std::io::prelude::*;
440+
/// use std::fs::File;
441+
///
442+
/// # fn foo() -> io::Result<()> {
443+
/// let mut f1 = try!(File::open("foo.txt"));
444+
/// let mut f2 = try!(File::open("bar.txt"));
445+
///
446+
/// let mut handle = f1.chain(f2);
447+
/// let mut buffer = String::new();
448+
///
449+
/// // read the value into a String. We could use any Read method here,
450+
/// // this is just one example.
451+
/// try!(handle.read_to_string(&mut buffer));
452+
/// # Ok(())
453+
/// # }
454+
/// ```
258455
#[stable(feature = "rust1", since = "1.0.0")]
259456
fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
260457
Chain { first: self, second: next, done_first: false }
@@ -266,6 +463,29 @@ pub trait Read {
266463
/// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
267464
/// read errors will not count towards the number of bytes read and future
268465
/// calls to `read` may succeed.
466+
///
467+
/// # Examples
468+
///
469+
/// [`File`][file]s implement `Read`:
470+
///
471+
/// [file]: ../std/fs/struct.File.html
472+
///
473+
/// ```
474+
/// use std::io;
475+
/// use std::io::prelude::*;
476+
/// use std::fs::File;
477+
///
478+
/// # fn foo() -> io::Result<()> {
479+
/// let mut f = try!(File::open("foo.txt"));
480+
/// let mut buffer = [0; 10];
481+
///
482+
/// // read at most five bytes
483+
/// let mut handle = f.take(5);
484+
///
485+
/// try!(handle.read(&mut buffer));
486+
/// # Ok(())
487+
/// # }
488+
/// ```
269489
#[stable(feature = "rust1", since = "1.0.0")]
270490
fn take(self, limit: u64) -> Take<Self> where Self: Sized {
271491
Take { inner: self, limit: limit }
@@ -277,6 +497,31 @@ pub trait Read {
277497
/// Whenever the returned `Read` instance is read it will write the read
278498
/// data to `out`. The current semantics of this implementation imply that
279499
/// a `write` error will not report how much data was initially read.
500+
///
501+
/// # Examples
502+
///
503+
/// [`File`][file]s implement `Read`:
504+
///
505+
/// [file]: ../std/fs/struct.File.html
506+
///
507+
/// ```
508+
/// #![feature(io)]
509+
/// use std::io;
510+
/// use std::io::prelude::*;
511+
/// use std::fs::File;
512+
///
513+
/// # fn foo() -> io::Result<()> {
514+
/// let mut f = try!(File::open("foo.txt"));
515+
/// let mut buffer1 = Vec::with_capacity(10);
516+
/// let mut buffer2 = Vec::with_capacity(10);
517+
///
518+
/// // write the output to buffer1 as we read
519+
/// let mut handle = f.tee(&mut buffer1);
520+
///
521+
/// try!(handle.read(&mut buffer2));
522+
/// # Ok(())
523+
/// # }
524+
/// ```
280525
#[unstable(feature = "io", reason = "the semantics of a partial read/write \
281526
of where errors happen is currently \
282527
unclear and may change")]
@@ -293,9 +538,30 @@ pub trait Read {
293538
/// The `flush` method is useful for adaptors and explicit buffers themselves
294539
/// for ensuring that all buffered data has been pushed out to the "true sink".
295540
///
296-
/// Writers are intended to be composable with one another. Many objects
297-
/// throughout the I/O and related libraries take and provide types which
298-
/// implement the `Write` trait.
541+
/// * The `write()` method will attempt to write some data into the object,
542+
/// returning how many bytes were successfully written.
543+
///
544+
/// * The `flush()` method is useful for adaptors and explicit buffers
545+
/// themselves for ensuring that all buffered data has been pushed out to the
546+
/// 'true sink'.
547+
///
548+
/// Writers are intended to be composable with one another. Many implementors
549+
/// throughout `std::io` take and provide types which implement the `Write`
550+
/// trait.
551+
///
552+
/// # Examples
553+
///
554+
/// ```
555+
/// use std::io::prelude::*;
556+
/// use std::fs::File;
557+
///
558+
/// # fn foo() -> std::io::Result<()> {
559+
/// let mut buffer = try!(File::create("foo.txt"));
560+
///
561+
/// try!(buffer.write(b"some bytes"));
562+
/// # Ok(())
563+
/// # }
564+
/// ```
299565
#[stable(feature = "rust1", since = "1.0.0")]
300566
pub trait Write {
301567
/// Write a buffer into this object, returning how many bytes were written.
@@ -508,8 +774,8 @@ fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
508774
/// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
509775
/// to perform extra ways of reading.
510776
///
511-
/// For example, reading line-by-line requires using a buffer, so if you want
512-
/// to read by line, you'll need `BufRead`, which includes a
777+
/// For example, reading line-by-line is inefficient without using a buffer, so
778+
/// if you want to read by line, you'll need `BufRead`, which includes a
513779
/// [`read_line()`][readline] method as well as a [`lines()`][lines] iterator.
514780
///
515781
/// [readline]: #method.read_line

0 commit comments

Comments
 (0)