Skip to content

Commit 30be6a6

Browse files
committed
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.
1 parent 46dcffd commit 30be6a6

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed

src/libcore/option.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,10 +295,16 @@ impl<T> Option<T> {
295295
pub fn expect(self, msg: &str) -> T {
296296
match self {
297297
Some(val) => val,
298-
None => panic!("{}", msg),
298+
None => Self::expect_failed(msg),
299299
}
300300
}
301301

302+
#[inline(never)]
303+
#[cold]
304+
fn expect_failed(msg: &str) -> ! {
305+
panic!("{}", msg)
306+
}
307+
302308
/// Moves the value `v` out of the `Option<T>` if it is `Some(v)`.
303309
///
304310
/// # Panics

src/libcore/result.rs

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -684,11 +684,16 @@ impl<T, E: fmt::Debug> Result<T, E> {
684684
pub fn unwrap(self) -> T {
685685
match self {
686686
Ok(t) => t,
687-
Err(e) =>
688-
panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
687+
Err(e) => Self::unwrap_failed(e),
689688
}
690689
}
691690

691+
#[inline(never)]
692+
#[cold]
693+
fn unwrap_failed(error: E) -> ! {
694+
panic!("called `Result::unwrap()` on an `Err` value: {:?}", error)
695+
}
696+
692697
/// Unwraps a result, yielding the content of an `Ok`.
693698
///
694699
/// # Panics
@@ -706,9 +711,15 @@ impl<T, E: fmt::Debug> Result<T, E> {
706711
pub fn expect(self, msg: &str) -> T {
707712
match self {
708713
Ok(t) => t,
709-
Err(e) => panic!("{}: {:?}", msg, e),
714+
Err(e) => Self::expect_failed(msg, e),
710715
}
711716
}
717+
718+
#[inline(never)]
719+
#[cold]
720+
fn expect_failed(msg: &str, error: E) -> ! {
721+
panic!("{}: {:?}", msg, error)
722+
}
712723
}
713724

714725
impl<T: fmt::Debug, E> Result<T, E> {
@@ -734,11 +745,17 @@ impl<T: fmt::Debug, E> Result<T, E> {
734745
#[stable(feature = "rust1", since = "1.0.0")]
735746
pub fn unwrap_err(self) -> E {
736747
match self {
737-
Ok(t) =>
738-
panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
739-
Err(e) => e
748+
Ok(t) => Self::unwrap_err_failed(t),
749+
Err(e) => e,
740750
}
741751
}
752+
753+
#[inline(never)]
754+
#[cold]
755+
fn unwrap_err_failed(t: T) -> ! {
756+
panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t)
757+
}
758+
742759
}
743760

744761
/////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)