From a8649ac5f282aea8798256162eedaae24cf71b65 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 20 Oct 2022 15:17:32 -0700 Subject: [PATCH] Remove 2 frames of backtrace noise on Option's Context impl Repro: use anyhow::Context; fn main() -> anyhow::Result<()> { let result = None::<()>; result.context("...") } Before: 0: anyhow::context:: for core::option::Option>::context::{{closure}} at /git/anyhow/src/context.rs:95:57 1: core::option::Option::ok_or_else at /rustc/4b8f4319954ff2642690b9e5cbe4af352d095bf6/library/core/src/option.rs:1083:25 2: anyhow::context:: for core::option::Option>::context at /git/anyhow/src/context.rs:95:9 3: testing::main at ./src/main.rs:5:5 After: 0: anyhow::context:: for core::option::Option>::context at /git/anyhow/src/context.rs:99:54 1: testing::main at ./src/main.rs:5:5 --- src/context.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/context.rs b/src/context.rs index 238473e..c8bd4f0 100644 --- a/src/context.rs +++ b/src/context.rs @@ -92,7 +92,12 @@ impl Context for Option { where C: Display + Send + Sync + 'static, { - self.ok_or_else(|| Error::from_display(context, backtrace!())) + // Not using ok_or_else to save 2 useless frames off the captured + // backtrace. + match self { + Some(ok) => Ok(ok), + None => Err(Error::from_display(context, backtrace!())), + } } fn with_context(self, context: F) -> Result @@ -100,7 +105,10 @@ impl Context for Option { C: Display + Send + Sync + 'static, F: FnOnce() -> C, { - self.ok_or_else(|| Error::from_display(context(), backtrace!())) + match self { + Some(ok) => Ok(ok), + None => Err(Error::from_display(context(), backtrace!())), + } } }