about summary refs log tree commit diff
path: root/library/std/src
diff options
context:
space:
mode:
authorCamelid <camelidcamel@gmail.com>2020-11-05 00:44:42 -0800
committerCamelid <camelidcamel@gmail.com>2020-12-19 21:46:40 -0800
commit1f9a8a1620a677d668c981a8e6be3ce02ef06cd5 (patch)
treef0fd43feb0e964af9c49031703495130bced0567 /library/std/src
parent0c11b93f5a8914a40f619b0a1663baafe029d427 (diff)
downloadrust-1f9a8a1620a677d668c981a8e6be3ce02ef06cd5.tar.gz
rust-1f9a8a1620a677d668c981a8e6be3ce02ef06cd5.zip
Add a `std::io::read_to_string` function
The equivalent of `std::fs::read_to_string`, but generalized to all
`Read` impls.

As the documentation on `std::io::read_to_string` says, the advantage of
this function is that it means you don't have to create a variable first
and it provides more type safety since you can only get the buffer out
if there were no errors. If you use `Read::read_to_string`, you have to
remember to check whether the read succeeded because otherwise your
buffer will be empty.

It's friendlier to newcomers and better in most cases to use an explicit
return value instead of an out parameter.
Diffstat (limited to 'library/std/src')
-rw-r--r--library/std/src/io/mod.rs27
1 files changed, 27 insertions, 0 deletions
diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs
index dfbf6c3f244..7a1896e4e59 100644
--- a/library/std/src/io/mod.rs
+++ b/library/std/src/io/mod.rs
@@ -945,6 +945,33 @@ pub trait Read {
     }
 }
 
+/// Convenience function for [`Read::read_to_string`].
+///
+/// This avoids having to create a variable first and it provides more type safety
+/// since you can only get the buffer out if there were no errors. (If you use
+/// [`Read::read_to_string`] you have to remember to check whether the read succeeded
+/// because otherwise your buffer will be empty.)
+///
+/// # Examples
+///
+/// ```no_run
+/// #![feature(io_read_to_string)]
+///
+/// # use std::io;
+/// fn main() -> io::Result<()> {
+///     let stdin = io::read_to_string(&mut io::stdin())?;
+///     println!("Stdin was:");
+///     println!("{}", stdin);
+///     Ok(())
+/// }
+/// ```
+#[unstable(feature = "io_read_to_string", issue = "80218")]
+pub fn read_to_string<R: Read>(reader: &mut R) -> Result<String> {
+    let mut buf = String::new();
+    reader.read_to_string(&mut buf)?;
+    Ok(buf)
+}
+
 /// A buffer type used with `Read::read_vectored`.
 ///
 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be