Skip to content
Myr

Merge pull request #19 from dtolnay/infer

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Consolidate to one Context impl for Result to improve inference

authored by David Tolnay · committed by GitHub · parents f9ca23f, c695e63 · Browse files · 2 files+43 added−23 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+43 added−23 removed

  • tests:+10 added−0 removed
  • other:+33 added−23 removed

2 files+43 added−23 removed

modified:src/context.rs+33 added-23 removed
63 unmodified lines
64 C: Display + Send + Sync + 'static,65 F: FnOnce() -> C;66}6768impl<T, E> Context<T, E> for Result<T, E>69where70 E: StdError + Send + Sync + 'static,71{72 fn context<C>(self, context: C) -> Result<T, Error>73 where74 C: Display + Send + Sync + 'static,75 {76 self.map_err(|error| Error::new(ContextError { error, context }))68mod ext {69 use super::*;7071 pub trait StdError {72 fn ext_context<C>(self, context: C) -> Error73 where74 C: Display + Send + Sync + 'static;75 }7679 fn with_context<C, F>(self, context: F) -> Result<T, Error>77 impl<E> StdError for E78 where81 C: Display + Send + Sync + 'static,82 F: FnOnce() -> C,79 E: std::error::Error + Send + Sync + 'static,80 {84 self.map_err(|error| {81 fn ext_context<C>(self, context: C) -> Error82 where83 C: Display + Send + Sync + 'static,84 {85 Error::new(ContextError {86 error,87 context: context(),86 error: self,87 context,88 })89 })89 }90 }9192 impl StdError for Error {93 fn ext_context<C>(self, context: C) -> Error94 where95 C: Display + Send + Sync + 'static,96 {97 self.context(context)98 }99 }100}10193impl<T> Context<T, Error> for Result<T, Error> {102impl<T, E> Context<T, E> for Result<T, E>103where104 E: ext::StdError + Send + Sync + 'static,105{106 fn context<C>(self, context: C) -> Result<T, Error>107 where108 C: Display + Send + Sync + 'static,109 {98 self.map_err(|error| error.context(context))110 self.map_err(|error| error.ext_context(context))111 }112113 fn with_context<C, F>(self, context: F) -> Result<T, Error>114 where115 C: Display + Send + Sync + 'static,116 F: FnOnce() -> C,117 {106 self.map_err(|error| error.context(context()))118 self.map_err(|error| error.ext_context(context()))119 }120}121122/// ```
86 unmodified lines
209 }210}211212mod private {201 use crate::Error;202 use std::error::Error as StdError;213 use super::*;214215 pub trait Sealed {}216206 impl<T, E> Sealed for Result<T, E> where E: StdError + Send + Sync + 'static {}207 impl<T> Sealed for Result<T, Error> {}217 impl<T, E> Sealed for Result<T, E> where E: ext::StdError {}218 impl<T> Sealed for Option<T> {}219}
added:tests/test_context.rs+10 added
1use anyhow::{Context, Result};23// https://github.com/dtolnay/anyhow/issues/184#[test]5fn test_inference() -> Result<()> {6 let x = "1";7 let y: u32 = x.parse().context("...")?;8 assert_eq!(y, 1);9 Ok(())10}