mirror of
https://github.com/rust-lang/rust.git
synced 2024-10-30 22:12:15 +00:00
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
This commit is contained in:
parent
44e9e0a6cf
commit
f2017f4561
@ -524,6 +524,7 @@ use string;
|
|||||||
pub fn format(args: Arguments) -> string::String {
|
pub fn format(args: Arguments) -> string::String {
|
||||||
let capacity = args.estimated_capacity();
|
let capacity = args.estimated_capacity();
|
||||||
let mut output = string::String::with_capacity(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
|
output
|
||||||
}
|
}
|
||||||
|
@ -72,6 +72,12 @@ macro_rules! vec {
|
|||||||
///
|
///
|
||||||
/// [fmt]: ../std/fmt/index.html
|
/// [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
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
|
@ -1888,13 +1888,20 @@ pub trait ToString {
|
|||||||
fn to_string(&self) -> String;
|
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")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
impl<T: fmt::Display + ?Sized> ToString for T {
|
impl<T: fmt::Display + ?Sized> ToString for T {
|
||||||
#[inline]
|
#[inline]
|
||||||
default fn to_string(&self) -> String {
|
default fn to_string(&self) -> String {
|
||||||
use core::fmt::Write;
|
use core::fmt::Write;
|
||||||
let mut buf = String::new();
|
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.shrink_to_fit();
|
||||||
buf
|
buf
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user