Skip to content

Commit 6375add

Browse files
Rollup merge of rust-lang#35109 - GuillaumeGomez:io_docs, r=steveklabnik
Add io::Error doc examples Fixes rust-lang#29359. r? @steveklabnik
2 parents a912d48 + fda473f commit 6375add

File tree

3 files changed

+222
-2
lines changed

3 files changed

+222
-2
lines changed

src/libstd/io/error.rs

+152-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ pub type Result<T> = result::Result<T, Error>;
5555
///
5656
/// Errors mostly originate from the underlying OS, but custom instances of
5757
/// `Error` can be created with crafted error messages and a particular value of
58-
/// `ErrorKind`.
58+
/// [`ErrorKind`].
59+
///
60+
/// [`ErrorKind`]: enum.ErrorKind.html
5961
#[derive(Debug)]
6062
#[stable(feature = "rust1", since = "1.0.0")]
6163
pub struct Error {
@@ -77,6 +79,10 @@ struct Custom {
7779
///
7880
/// This list is intended to grow over time and it is not recommended to
7981
/// exhaustively match against it.
82+
///
83+
/// It is used with the [`io::Error`] type.
84+
///
85+
/// [`io::Error`]: struct.Error.html
8086
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
8187
#[stable(feature = "rust1", since = "1.0.0")]
8288
#[allow(deprecated)]
@@ -208,6 +214,14 @@ impl Error {
208214
/// This function reads the value of `errno` for the target platform (e.g.
209215
/// `GetLastError` on Windows) and will return a corresponding instance of
210216
/// `Error` for the error code.
217+
///
218+
/// # Examples
219+
///
220+
/// ```
221+
/// use std::io::Error;
222+
///
223+
/// println!("last OS error: {:?}", Error::last_os_error());
224+
/// ```
211225
#[stable(feature = "rust1", since = "1.0.0")]
212226
pub fn last_os_error() -> Error {
213227
Error::from_raw_os_error(sys::os::errno() as i32)
@@ -248,6 +262,27 @@ impl Error {
248262
/// If this `Error` was constructed via `last_os_error` or
249263
/// `from_raw_os_error`, then this function will return `Some`, otherwise
250264
/// it will return `None`.
265+
///
266+
/// # Examples
267+
///
268+
/// ```
269+
/// use std::io::{Error, ErrorKind};
270+
///
271+
/// fn print_os_error(err: &Error) {
272+
/// if let Some(raw_os_err) = err.raw_os_error() {
273+
/// println!("raw OS error: {:?}", raw_os_err);
274+
/// } else {
275+
/// println!("Not an OS error");
276+
/// }
277+
/// }
278+
///
279+
/// fn main() {
280+
/// // Will print "raw OS error: ...".
281+
/// print_os_error(&Error::last_os_error());
282+
/// // Will print "Not an OS error".
283+
/// print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
284+
/// }
285+
/// ```
251286
#[stable(feature = "rust1", since = "1.0.0")]
252287
pub fn raw_os_error(&self) -> Option<i32> {
253288
match self.repr {
@@ -260,6 +295,27 @@ impl Error {
260295
///
261296
/// If this `Error` was constructed via `new` then this function will
262297
/// return `Some`, otherwise it will return `None`.
298+
///
299+
/// # Examples
300+
///
301+
/// ```
302+
/// use std::io::{Error, ErrorKind};
303+
///
304+
/// fn print_error(err: &Error) {
305+
/// if let Some(inner_err) = err.get_ref() {
306+
/// println!("Inner error: {:?}", inner_err);
307+
/// } else {
308+
/// println!("No inner error");
309+
/// }
310+
/// }
311+
///
312+
/// fn main() {
313+
/// // Will print "No inner error".
314+
/// print_error(&Error::last_os_error());
315+
/// // Will print "Inner error: ...".
316+
/// print_error(&Error::new(ErrorKind::Other, "oh no!"));
317+
/// }
318+
/// ```
263319
#[stable(feature = "io_error_inner", since = "1.3.0")]
264320
pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> {
265321
match self.repr {
@@ -273,6 +329,63 @@ impl Error {
273329
///
274330
/// If this `Error` was constructed via `new` then this function will
275331
/// return `Some`, otherwise it will return `None`.
332+
///
333+
/// # Examples
334+
///
335+
/// ```
336+
/// use std::io::{Error, ErrorKind};
337+
/// use std::{error, fmt};
338+
/// use std::fmt::Display;
339+
///
340+
/// #[derive(Debug)]
341+
/// struct MyError {
342+
/// v: String,
343+
/// }
344+
///
345+
/// impl MyError {
346+
/// fn new() -> MyError {
347+
/// MyError {
348+
/// v: "oh no!".to_owned()
349+
/// }
350+
/// }
351+
///
352+
/// fn change_message(&mut self, new_message: &str) {
353+
/// self.v = new_message.to_owned();
354+
/// }
355+
/// }
356+
///
357+
/// impl error::Error for MyError {
358+
/// fn description(&self) -> &str { &self.v }
359+
/// }
360+
///
361+
/// impl Display for MyError {
362+
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
363+
/// write!(f, "MyError: {}", &self.v)
364+
/// }
365+
/// }
366+
///
367+
/// fn change_error(mut err: Error) -> Error {
368+
/// if let Some(inner_err) = err.get_mut() {
369+
/// inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
370+
/// }
371+
/// err
372+
/// }
373+
///
374+
/// fn print_error(err: &Error) {
375+
/// if let Some(inner_err) = err.get_ref() {
376+
/// println!("Inner error: {}", inner_err);
377+
/// } else {
378+
/// println!("No inner error");
379+
/// }
380+
/// }
381+
///
382+
/// fn main() {
383+
/// // Will print "No inner error".
384+
/// print_error(&change_error(Error::last_os_error()));
385+
/// // Will print "Inner error: ...".
386+
/// print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
387+
/// }
388+
/// ```
276389
#[stable(feature = "io_error_inner", since = "1.3.0")]
277390
pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> {
278391
match self.repr {
@@ -285,6 +398,27 @@ impl Error {
285398
///
286399
/// If this `Error` was constructed via `new` then this function will
287400
/// return `Some`, otherwise it will return `None`.
401+
///
402+
/// # Examples
403+
///
404+
/// ```
405+
/// use std::io::{Error, ErrorKind};
406+
///
407+
/// fn print_error(err: Error) {
408+
/// if let Some(inner_err) = err.into_inner() {
409+
/// println!("Inner error: {}", inner_err);
410+
/// } else {
411+
/// println!("No inner error");
412+
/// }
413+
/// }
414+
///
415+
/// fn main() {
416+
/// // Will print "No inner error".
417+
/// print_error(Error::last_os_error());
418+
/// // Will print "Inner error: ...".
419+
/// print_error(Error::new(ErrorKind::Other, "oh no!"));
420+
/// }
421+
/// ```
288422
#[stable(feature = "io_error_inner", since = "1.3.0")]
289423
pub fn into_inner(self) -> Option<Box<error::Error+Send+Sync>> {
290424
match self.repr {
@@ -294,6 +428,23 @@ impl Error {
294428
}
295429

296430
/// Returns the corresponding `ErrorKind` for this error.
431+
///
432+
/// # Examples
433+
///
434+
/// ```
435+
/// use std::io::{Error, ErrorKind};
436+
///
437+
/// fn print_error(err: Error) {
438+
/// println!("{:?}", err.kind());
439+
/// }
440+
///
441+
/// fn main() {
442+
/// // Will print "No inner error".
443+
/// print_error(Error::last_os_error());
444+
/// // Will print "Inner error: ...".
445+
/// print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
446+
/// }
447+
/// ```
297448
#[stable(feature = "rust1", since = "1.0.0")]
298449
pub fn kind(&self) -> ErrorKind {
299450
match self.repr {

src/libstd/io/mod.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -1082,16 +1082,22 @@ pub trait Seek {
10821082
///
10831083
/// If the seek operation completed successfully,
10841084
/// this method returns the new position from the start of the stream.
1085-
/// That position can be used later with `SeekFrom::Start`.
1085+
/// That position can be used later with [`SeekFrom::Start`].
10861086
///
10871087
/// # Errors
10881088
///
10891089
/// Seeking to a negative offset is considered an error.
1090+
///
1091+
/// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
10901092
#[stable(feature = "rust1", since = "1.0.0")]
10911093
fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
10921094
}
10931095

10941096
/// Enumeration of possible methods to seek within an I/O object.
1097+
///
1098+
/// It is used by the [`Seek`] trait.
1099+
///
1100+
/// [`Seek`]: trait.Seek.html
10951101
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
10961102
#[stable(feature = "rust1", since = "1.0.0")]
10971103
pub enum SeekFrom {
@@ -1482,6 +1488,24 @@ impl<T> Take<T> {
14821488
///
14831489
/// This instance may reach EOF after reading fewer bytes than indicated by
14841490
/// this method if the underlying `Read` instance reaches EOF.
1491+
///
1492+
/// # Examples
1493+
///
1494+
/// ```
1495+
/// use std::io;
1496+
/// use std::io::prelude::*;
1497+
/// use std::fs::File;
1498+
///
1499+
/// # fn foo() -> io::Result<()> {
1500+
/// let f = try!(File::open("foo.txt"));
1501+
///
1502+
/// // read at most five bytes
1503+
/// let handle = f.take(5);
1504+
///
1505+
/// println!("limit: {}", handle.limit());
1506+
/// # Ok(())
1507+
/// # }
1508+
/// ```
14851509
#[stable(feature = "rust1", since = "1.0.0")]
14861510
pub fn limit(&self) -> u64 { self.limit }
14871511
}

src/libstd/io/stdio.rs

+45
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,21 @@ impl Stdin {
240240
///
241241
/// [`Read`]: trait.Read.html
242242
/// [`BufRead`]: trait.BufRead.html
243+
///
244+
/// # Examples
245+
///
246+
/// ```
247+
/// use std::io::{self, Read};
248+
///
249+
/// # fn foo() -> io::Result<String> {
250+
/// let mut buffer = String::new();
251+
/// let stdin = io::stdin();
252+
/// let mut handle = stdin.lock();
253+
///
254+
/// try!(handle.read_to_string(&mut buffer));
255+
/// # Ok(buffer)
256+
/// # }
257+
/// ```
243258
#[stable(feature = "rust1", since = "1.0.0")]
244259
pub fn lock(&self) -> StdinLock {
245260
StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
@@ -399,6 +414,21 @@ impl Stdout {
399414
///
400415
/// The lock is released when the returned lock goes out of scope. The
401416
/// returned guard also implements the `Write` trait for writing data.
417+
///
418+
/// # Examples
419+
///
420+
/// ```
421+
/// use std::io::{self, Write};
422+
///
423+
/// # fn foo() -> io::Result<()> {
424+
/// let stdout = io::stdout();
425+
/// let mut handle = stdout.lock();
426+
///
427+
/// try!(handle.write(b"hello world"));
428+
///
429+
/// # Ok(())
430+
/// # }
431+
/// ```
402432
#[stable(feature = "rust1", since = "1.0.0")]
403433
pub fn lock(&self) -> StdoutLock {
404434
StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
@@ -505,6 +535,21 @@ impl Stderr {
505535
///
506536
/// The lock is released when the returned lock goes out of scope. The
507537
/// returned guard also implements the `Write` trait for writing data.
538+
///
539+
/// # Examples
540+
///
541+
/// ```
542+
/// use std::io::{self, Write};
543+
///
544+
/// fn foo() -> io::Result<()> {
545+
/// let stderr = io::stderr();
546+
/// let mut handle = stderr.lock();
547+
///
548+
/// try!(handle.write(b"hello world"));
549+
///
550+
/// Ok(())
551+
/// }
552+
/// ```
508553
#[stable(feature = "rust1", since = "1.0.0")]
509554
pub fn lock(&self) -> StderrLock {
510555
StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }

0 commit comments

Comments
 (0)