提交 30be6a66 编写于 作者: U Ulrik Sverdrup

Use cold functions for panic formatting Option::expect, Result::unwrap etc

Option::expect, Result::unwrap, unwrap_err, expect

These methods are marked inline, but insert a big chunk of formatting
code, as well as other error path related code, such as deallocating
a std::io::Error if you have one.

We can explicitly separate out that code path into a function that is
never inline, since the panicking case should always be rare.
上级 46dcffd0
......@@ -295,10 +295,16 @@ pub fn as_mut(&mut self) -> Option<&mut T> {
pub fn expect(self, msg: &str) -> T {
match self {
Some(val) => val,
None => panic!("{}", msg),
None => Self::expect_failed(msg),
}
}
#[inline(never)]
#[cold]
fn expect_failed(msg: &str) -> ! {
panic!("{}", msg)
}
/// Moves the value `v` out of the `Option<T>` if it is `Some(v)`.
///
/// # Panics
......
......@@ -684,11 +684,16 @@ impl<T, E: fmt::Debug> Result<T, E> {
pub fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) =>
panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
Err(e) => Self::unwrap_failed(e),
}
}
#[inline(never)]
#[cold]
fn unwrap_failed(error: E) -> ! {
panic!("called `Result::unwrap()` on an `Err` value: {:?}", error)
}
/// Unwraps a result, yielding the content of an `Ok`.
///
/// # Panics
......@@ -706,9 +711,15 @@ pub fn unwrap(self) -> T {
pub fn expect(self, msg: &str) -> T {
match self {
Ok(t) => t,
Err(e) => panic!("{}: {:?}", msg, e),
Err(e) => Self::expect_failed(msg, e),
}
}
#[inline(never)]
#[cold]
fn expect_failed(msg: &str, error: E) -> ! {
panic!("{}: {:?}", msg, error)
}
}
impl<T: fmt::Debug, E> Result<T, E> {
......@@ -734,11 +745,17 @@ impl<T: fmt::Debug, E> Result<T, E> {
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unwrap_err(self) -> E {
match self {
Ok(t) =>
panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
Err(e) => e
Ok(t) => Self::unwrap_err_failed(t),
Err(e) => e,
}
}
#[inline(never)]
#[cold]
fn unwrap_err_failed(t: T) -> ! {
panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t)
}
}
/////////////////////////////////////////////////////////////////////////////
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册