From 95ace50643218f97849a8073bb201583f9639fdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20T=C3=A9tar?= Date: Thu, 2 Jan 2014 13:35:08 +0100 Subject: [PATCH] std: io: add some code examples Closes #11232. --- src/libstd/io/mod.rs | 66 ++++++++++++++++++++++++++++++-------------- 1 file changed, 45 insertions(+), 21 deletions(-) diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 13d67ff354a83..86bad7a228b0a 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -186,23 +186,29 @@ while still providing feedback about errors. The basic strategy: so that nullable values do not have to be 'unwrapped' before use. These features combine in the API to allow for expressions like -`File::new("diary.txt").write_line("met a girl")` without having to -worry about whether "diary.txt" exists or whether the write -succeeds. As written, if either `new` or `write_line` encounters -an error the task will fail. - -If you wanted to handle the error though you might write - - let mut error = None; - do io_error::cond(|e: IoError| { - error = Some(e); - }).in { - File::new("diary.txt").write_line("met a girl"); - } - - if error.is_some() { - println("failed to write my diary"); - } +`File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n"))` +without having to worry about whether "diary.txt" exists or whether +the write succeeds. As written, if either `new` or `write_line` +encounters an error the task will fail. + +If you wanted to handle the error though you might write: + +```rust +use std::io::File; +use std::io::{IoError, io_error}; + +let mut error = None; +io_error::cond.trap(|e: IoError| { + error = Some(e); +}).inside(|| { + File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n")); +}); + +if error.is_some() { + println("failed to write my diary"); +} +# ::std::io::fs::unlink(&Path::new("diary.txt")); +``` XXX: Need better condition handling syntax @@ -498,10 +504,16 @@ pub trait Reader { /// /// # Example /// - /// let mut reader = BufferedReader::new(File::open(&Path::new("foo.txt"))); - /// for line in reader.lines() { - /// println(line); - /// } + /// ```rust + /// use std::io; + /// # let _g = ::std::io::ignore_io_error(); + /// let mut reader = io::stdin(); + /// + /// let mut bytes = [0, .. 10]; + /// reader.read(bytes); + /// + /// if reader.eof() { println("stdin() had at most 10 bytes of data."); } + /// ``` /// /// # Failure /// @@ -1057,6 +1069,18 @@ pub trait Buffer: Reader { /// encoded unicode codepoints. If a newline is encountered, then the /// newline is contained in the returned string. /// + /// # Example + /// + /// ```rust + /// use std::io::buffered::BufferedReader; + /// use std::io; + /// # let _g = ::std::io::ignore_io_error(); + /// + /// let mut reader = BufferedReader::new(io::stdin()); + /// + /// let input = reader.read_line().unwrap_or(~"nothing"); + /// ``` + /// /// # Failure /// /// This function will raise on the `io_error` condition (except for