Skip to content

Commit a7c7a4e

Browse files
authored
Rollup merge of rust-lang#40117 - SimonSapin:to-err-is-for-the-formatter, 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
2 parents ec4bcc6 + f2017f4 commit a7c7a4e

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

src/libcollections/fmt.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,7 @@ use string;
524524
pub fn format(args: Arguments) -> string::String {
525525
let capacity = args.estimated_capacity();
526526
let mut output = string::String::with_capacity(capacity);
527-
let _ = output.write_fmt(args);
527+
output.write_fmt(args)
528+
.expect("a formatting trait implementation returned an error");
528529
output
529530
}

src/libcollections/macros.rs

+6
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,12 @@ macro_rules! vec {
7272
///
7373
/// [fmt]: ../std/fmt/index.html
7474
///
75+
/// # Panics
76+
///
77+
/// `format!` panics if a formatting trait implementation returns an error.
78+
/// This indicates an incorrect implementation
79+
/// since `fmt::Write for String` never returns an error itself.
80+
///
7581
/// # Examples
7682
///
7783
/// ```

src/libcollections/string.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -1900,13 +1900,20 @@ pub trait ToString {
19001900
fn to_string(&self) -> String;
19011901
}
19021902

1903+
/// # Panics
1904+
///
1905+
/// In this implementation, the `to_string` method panics
1906+
/// if the `Display` implementation returns an error.
1907+
/// This indicates an incorrect `Display` implementation
1908+
/// since `fmt::Write for String` never returns an error itself.
19031909
#[stable(feature = "rust1", since = "1.0.0")]
19041910
impl<T: fmt::Display + ?Sized> ToString for T {
19051911
#[inline]
19061912
default fn to_string(&self) -> String {
19071913
use core::fmt::Write;
19081914
let mut buf = String::new();
1909-
let _ = buf.write_fmt(format_args!("{}", self));
1915+
buf.write_fmt(format_args!("{}", self))
1916+
.expect("a Display implementation return an error unexpectedly");
19101917
buf.shrink_to_fit();
19111918
buf
19121919
}

0 commit comments

Comments
 (0)