diff options
| author | Corey Farwell <coreyf@rwell.org> | 2017-03-02 14:53:44 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2017-03-02 14:53:44 -0500 |
| commit | 0536fd6396133189fb4a41377d3972cd312078a0 (patch) | |
| tree | 7d4aa4ac6b26a96ee2817015ea498d5253dc84b1 | |
| parent | aef07cd991d9b014e74684416ac032f6531cb93c (diff) | |
| parent | f2017f4561852bf65c39fc498cf035a5f385a065 (diff) | |
Rollup merge of #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 #40103
| -rw-r--r-- | src/libcollections/fmt.rs | 3 | ||||
| -rw-r--r-- | src/libcollections/macros.rs | 6 | ||||
| -rw-r--r-- | src/libcollections/string.rs | 9 |
3 files changed, 16 insertions, 2 deletions
diff --git a/src/libcollections/fmt.rs b/src/libcollections/fmt.rs index 079541235a2..dfd292176d2 100644 --- a/src/libcollections/fmt.rs +++ b/src/libcollections/fmt.rs @@ -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 } diff --git a/src/libcollections/macros.rs b/src/libcollections/macros.rs index 3115be00a4d..396a917dfde 100644 --- a/src/libcollections/macros.rs +++ b/src/libcollections/macros.rs @@ -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 /// /// ``` diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 4b37aef860d..f2e4be49684 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -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 } |
