1use core::convert::Infallible;
2use std::fmt::Display;
3use std::panic::Location;
4
5pub use anyhow::{anyhow, bail, ensure};
7pub use anyhow::{Chain, Error, Ok, Result};
8
9pub trait Context<T, E> {
10 fn context<C>(self, context: C) -> Result<T>
11 where
12 C: Display + Send + Sync + 'static;
13
14 fn with_context<C, F>(self, context: F) -> Result<T>
15 where
16 C: Display + Send + Sync + 'static,
17 F: FnOnce() -> C;
18
19 fn dot(self) -> Result<T>;
21}
22
23impl<T, E> Context<T, E> for Result<T, E>
24where
25 E: Display,
26 Result<T, E>: anyhow::Context<T, E>,
27{
28 #[inline]
29 #[track_caller]
30 fn context<C>(self, context: C) -> Result<T>
31 where
32 C: Display + Send + Sync + 'static,
33 {
34 let caller = Location::caller();
35 anyhow::Context::context(self, format!("{} at `{}:{}:{}`", context, caller.file(), caller.line(), caller.column()))
36 }
37
38 #[inline]
39 #[track_caller]
40 fn with_context<C, F>(self, context: F) -> Result<T>
41 where
42 C: Display + Send + Sync + 'static,
43 F: FnOnce() -> C,
44 {
45 let caller = Location::caller();
46 anyhow::Context::with_context(self, || {
47 format!("{} at `{}:{}:{}`", context(), caller.file(), caller.line(), caller.column(),)
48 })
49 }
50
51 #[inline]
52 #[track_caller]
53 fn dot(self) -> Result<T> {
54 let caller = Location::caller();
55 anyhow::Context::context(self, format!("at `{}:{}:{}`", caller.file(), caller.line(), caller.column()))
56 }
57}
58
59impl<T> Context<T, Infallible> for Option<T>
60where
61 Option<T>: anyhow::Context<T, Infallible>,
62{
63 #[inline]
64 #[track_caller]
65 fn context<C>(self, context: C) -> Result<T, Error>
66 where
67 C: Display + Send + Sync + 'static,
68 {
69 let caller = Location::caller();
70 anyhow::Context::context(self, format!("{} at `{}:{}:{}`", context, caller.file(), caller.line(), caller.column()))
71 }
72
73 #[inline]
74 #[track_caller]
75 fn with_context<C, F>(self, context: F) -> Result<T, Error>
76 where
77 C: Display + Send + Sync + 'static,
78 F: FnOnce() -> C,
79 {
80 let caller = Location::caller();
81 anyhow::Context::with_context(self, || {
82 format!("{} at `{}:{}:{}`", context(), caller.file(), caller.line(), caller.column(),)
83 })
84 }
85
86 #[inline]
87 #[track_caller]
88 fn dot(self) -> Result<T> {
89 let caller = Location::caller();
90 anyhow::Context::context(self, format!("at `{}:{}:{}`", caller.file(), caller.line(), caller.column()))
91 }
92}