Skip to content

Use cold functions for panic formatting Option::expect, Result::unwra… #31116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 23, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ impl<T> Option<T> {
pub fn expect(self, msg: &str) -> T {
match self {
Some(val) => val,
None => panic!("{}", msg),
None => expect_failed(msg),
}
}

Expand Down Expand Up @@ -697,6 +697,14 @@ impl<T: Default> Option<T> {
}
}

// This is a separate function to reduce the code size of .expect() itself.
#[inline(never)]
#[cold]
fn expect_failed(msg: &str) -> ! {
panic!("{}", msg)
}


/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
Expand Down
17 changes: 11 additions & 6 deletions src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,8 +684,7 @@ 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) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
}
}

Expand All @@ -706,7 +705,7 @@ impl<T, E: fmt::Debug> Result<T, E> {
pub fn expect(self, msg: &str) -> T {
match self {
Ok(t) => t,
Err(e) => panic!("{}: {:?}", msg, e),
Err(e) => unwrap_failed(msg, e),
}
}
}
Expand Down Expand Up @@ -734,13 +733,19 @@ 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) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
Err(e) => e,
}
}
}

// This is a separate function to reduce the code size of the methods
#[inline(never)]
#[cold]
fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
panic!("{}: {:?}", msg, error)
}

/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
Expand Down