Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a std::io::read_to_string function #80217

Merged
merged 4 commits into from
Jan 14, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions library/std/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.)
camelid marked this conversation as resolved.
Show resolved Hide resolved
///
camelid marked this conversation as resolved.
Show resolved Hide resolved
/// # 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();
m-ou-se marked this conversation as resolved.
Show resolved Hide resolved
reader.read_to_string(&mut buf)?;
Ok(buf)
}
camelid marked this conversation as resolved.
Show resolved Hide resolved

/// A buffer type used with `Read::read_vectored`.
///
/// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
Expand Down