1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
//! Additions to the [`TryFuture`] trait.
//!
//! [`TryFuture`]: futures_core_crate::future::TryFuture
use crate::{Error, ErrorCompat, FromString, IntoError};
use core::{
future::Future,
marker::PhantomData,
pin::Pin,
task::{Context as TaskContext, Poll},
};
use futures_core_crate::future::TryFuture;
use pin_project::pin_project;
/// Additions to [`TryFuture`].
pub trait TryFutureExt: TryFuture + Sized {
/// Extend a [`TryFuture`]'s error with additional context-sensitive
/// information.
///
/// ```rust
/// # use futures_crate as futures;
/// use futures::future::TryFuture;
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// enum Error {
/// Authenticating {
/// user_name: String,
/// user_id: i32,
/// source: ApiError,
/// },
/// }
///
/// fn example() -> impl TryFuture<Ok = i32, Error = Error> {
/// another_function().context(AuthenticatingSnafu {
/// user_name: "admin",
/// user_id: 42,
/// })
/// }
///
/// # type ApiError = Box<dyn std::error::Error>;
/// fn another_function() -> impl TryFuture<Ok = i32, Error = ApiError> {
/// /* ... */
/// # futures::future::ok(42)
/// }
/// ```
///
/// Note that the context selector will call [`Into::into`] on
/// each field, so the types are not required to exactly match.
fn context<C, E>(self, context: C) -> Context<Self, C, E>
where
C: IntoError<E, Source = Self::Error>,
E: Error + ErrorCompat;
/// Extend a [`TryFuture`]'s error with lazily-generated context-sensitive
/// information.
///
/// ```rust
/// # use futures_crate as futures;
/// use futures::future::TryFuture;
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// enum Error {
/// Authenticating {
/// user_name: String,
/// user_id: i32,
/// source: ApiError,
/// },
/// }
///
/// fn example() -> impl TryFuture<Ok = i32, Error = Error> {
/// another_function().with_context(|| AuthenticatingSnafu {
/// user_name: "admin".to_string(),
/// user_id: 42,
/// })
/// }
///
/// # type ApiError = Box<dyn std::error::Error>;
/// fn another_function() -> impl TryFuture<Ok = i32, Error = ApiError> {
/// /* ... */
/// # futures::future::ok(42)
/// }
/// ```
///
/// Note that this *may not* be needed in many cases because the
/// context selector will call [`Into::into`] on each field.
fn with_context<F, C, E>(self, context: F) -> WithContext<Self, F, E>
where
F: FnOnce() -> C,
C: IntoError<E, Source = Self::Error>,
E: Error + ErrorCompat;
/// Extend a [`TryFuture`]'s error with information from a string.
///
/// The target error type must implement [`FromString`] by using
/// the
/// [`#[snafu(whatever)]`][crate::Snafu#controlling-stringly-typed-errors]
/// attribute. The premade [`Whatever`](crate::Whatever) type is also available.
///
/// In many cases, you will want to use
/// [`with_whatever_context`][Self::with_whatever_context] instead
/// as it is only called in case of error. This method is best
/// suited for when you have a string literal.
///
/// ```rust
/// # use futures_crate as futures;
/// use futures::future::TryFuture;
/// use snafu::{prelude::*, Whatever};
///
/// fn example() -> impl TryFuture<Ok = i32, Error = Whatever> {
/// api_function().whatever_context("The API failed")
/// }
///
/// # type ApiError = Box<dyn std::error::Error>;
/// fn api_function() -> impl TryFuture<Ok = i32, Error = ApiError> {
/// /* ... */
/// # futures::future::ok(42)
/// }
/// ```
fn whatever_context<S, E>(self, context: S) -> WhateverContext<Self, S, E>
where
S: Into<String>,
E: FromString;
/// Extend a [`TryFuture`]'s error with information from a
/// lazily-generated string.
///
/// The target error type must implement [`FromString`] by using
/// the
/// [`#[snafu(whatever)]`][crate::Snafu#controlling-stringly-typed-errors]
/// attribute. The premade [`Whatever`](crate::Whatever) type is also available.
///
/// ```rust
/// # use futures_crate as futures;
/// use futures::future::TryFuture;
/// use snafu::{prelude::*, Whatever};
///
/// fn example(arg: &'static str) -> impl TryFuture<Ok = i32, Error = Whatever> {
/// api_function(arg)
/// .with_whatever_context(move |_| format!("The API failed for argument {}", arg))
/// }
///
/// # type ApiError = Box<dyn std::error::Error>;
/// fn api_function(arg: &'static str) -> impl TryFuture<Ok = i32, Error = ApiError> {
/// /* ... */
/// # futures::future::ok(42)
/// }
/// ```
fn with_whatever_context<F, S, E>(self, context: F) -> WithWhateverContext<Self, F, E>
where
F: FnOnce(&Self::Error) -> S,
S: Into<String>,
E: FromString;
}
impl<Fut> TryFutureExt for Fut
where
Fut: TryFuture,
{
fn context<C, E>(self, context: C) -> Context<Self, C, E>
where
C: IntoError<E, Source = Self::Error>,
E: Error + ErrorCompat,
{
Context {
inner: self,
context: Some(context),
_e: PhantomData,
}
}
fn with_context<F, C, E>(self, context: F) -> WithContext<Self, F, E>
where
F: FnOnce() -> C,
C: IntoError<E, Source = Self::Error>,
E: Error + ErrorCompat,
{
WithContext {
inner: self,
context: Some(context),
_e: PhantomData,
}
}
fn whatever_context<S, E>(self, context: S) -> WhateverContext<Self, S, E>
where
S: Into<String>,
E: FromString,
{
WhateverContext {
inner: self,
context: Some(context),
_e: PhantomData,
}
}
fn with_whatever_context<F, S, E>(self, context: F) -> WithWhateverContext<Self, F, E>
where
F: FnOnce(&Self::Error) -> S,
S: Into<String>,
E: FromString,
{
WithWhateverContext {
inner: self,
context: Some(context),
_e: PhantomData,
}
}
}
/// Future for the [`context`](TryFutureExt::context) combinator.
///
/// See the [`TryFutureExt::context`] method for more details.
#[pin_project]
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct Context<Fut, C, E> {
#[pin]
inner: Fut,
context: Option<C>,
_e: PhantomData<E>,
}
impl<Fut, C, E> Future for Context<Fut, C, E>
where
Fut: TryFuture,
C: IntoError<E, Source = Fut::Error>,
E: Error + ErrorCompat,
{
type Output = Result<Fut::Ok, E>;
fn poll(self: Pin<&mut Self>, ctx: &mut TaskContext) -> Poll<Self::Output> {
let this = self.project();
let inner = this.inner;
let context = this.context;
inner.try_poll(ctx).map_err(|error| {
context
.take()
.expect("Cannot poll Context after it resolves")
.into_error(error)
})
}
}
/// Future for the [`with_context`](TryFutureExt::with_context) combinator.
///
/// See the [`TryFutureExt::with_context`] method for more details.
#[pin_project]
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct WithContext<Fut, F, E> {
#[pin]
inner: Fut,
context: Option<F>,
_e: PhantomData<E>,
}
impl<Fut, F, C, E> Future for WithContext<Fut, F, E>
where
Fut: TryFuture,
F: FnOnce() -> C,
C: IntoError<E, Source = Fut::Error>,
E: Error + ErrorCompat,
{
type Output = Result<Fut::Ok, E>;
fn poll(self: Pin<&mut Self>, ctx: &mut TaskContext) -> Poll<Self::Output> {
let this = self.project();
let inner = this.inner;
let context = this.context;
inner.try_poll(ctx).map_err(|error| {
let context = context
.take()
.expect("Cannot poll WithContext after it resolves");
context().into_error(error)
})
}
}
/// Future for the
/// [`whatever_context`](TryFutureExt::whatever_context) combinator.
///
/// See the [`TryFutureExt::whatever_context`] method for more
/// details.
#[pin_project]
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct WhateverContext<Fut, S, E> {
#[pin]
inner: Fut,
context: Option<S>,
_e: PhantomData<E>,
}
impl<Fut, S, E> Future for WhateverContext<Fut, S, E>
where
Fut: TryFuture,
S: Into<String>,
E: FromString,
Fut::Error: Into<E::Source>,
{
type Output = Result<Fut::Ok, E>;
fn poll(self: Pin<&mut Self>, ctx: &mut TaskContext) -> Poll<Self::Output> {
let this = self.project();
let inner = this.inner;
let context = this.context;
inner.try_poll(ctx).map_err(|error| {
let context = context
.take()
.expect("Cannot poll WhateverContext after it resolves");
FromString::with_source(error.into(), context.into())
})
}
}
/// Future for the
/// [`with_whatever_context`](TryFutureExt::with_whatever_context)
/// combinator.
///
/// See the [`TryFutureExt::with_whatever_context`] method for more
/// details.
#[pin_project]
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct WithWhateverContext<Fut, F, E> {
#[pin]
inner: Fut,
context: Option<F>,
_e: PhantomData<E>,
}
impl<Fut, F, S, E> Future for WithWhateverContext<Fut, F, E>
where
Fut: TryFuture,
F: FnOnce(&Fut::Error) -> S,
S: Into<String>,
E: FromString,
Fut::Error: Into<E::Source>,
{
type Output = Result<Fut::Ok, E>;
fn poll(self: Pin<&mut Self>, ctx: &mut TaskContext) -> Poll<Self::Output> {
let this = self.project();
let inner = this.inner;
let context = this.context;
inner.try_poll(ctx).map_err(|error| {
let context = context
.take()
.expect("Cannot poll WhateverContext after it resolves");
let context = context(&error);
FromString::with_source(error.into(), context.into())
})
}
}