Skip to content

Commit

Permalink
Rollup merge of rust-lang#40117 - SimonSapin:to-err-is-for-the-format…
Browse files Browse the repository at this point in the history
…ter, r=alexcrichton

Panic on errors in `format!` or `<T: Display>::to_string`

… instead of silently ignoring a result.

`fmt::Write for String` never returns `Err`, so implementations of `Display` (or other traits of that family) never should either.

Fixes rust-lang#40103
  • Loading branch information
frewsxcv authored Mar 2, 2017
2 parents 21b39a8 + f2017f4 commit dcb2932
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/libcollections/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ use string;
pub fn format(args: Arguments) -> string::String {
let capacity = args.estimated_capacity();
let mut output = string::String::with_capacity(capacity);
let _ = output.write_fmt(args);
output.write_fmt(args)
.expect("a formatting trait implementation returned an error");
output
}
6 changes: 6 additions & 0 deletions src/libcollections/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ macro_rules! vec {
///
/// [fmt]: ../std/fmt/index.html
///
/// # Panics
///
/// `format!` panics if a formatting trait implementation returns an error.
/// This indicates an incorrect implementation
/// since `fmt::Write for String` never returns an error itself.
///
/// # Examples
///
/// ```
Expand Down
9 changes: 8 additions & 1 deletion src/libcollections/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1900,13 +1900,20 @@ pub trait ToString {
fn to_string(&self) -> String;
}

/// # Panics
///
/// In this implementation, the `to_string` method panics
/// if the `Display` implementation returns an error.
/// This indicates an incorrect `Display` implementation
/// since `fmt::Write for String` never returns an error itself.
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> ToString for T {
#[inline]
default fn to_string(&self) -> String {
use core::fmt::Write;
let mut buf = String::new();
let _ = buf.write_fmt(format_args!("{}", self));
buf.write_fmt(format_args!("{}", self))
.expect("a Display implementation return an error unexpectedly");
buf.shrink_to_fit();
buf
}
Expand Down

0 comments on commit dcb2932

Please sign in to comment.