|
| 1 | + |
| 2 | +use super::Compat; |
| 3 | +use crate::{TryFutureExt, FutureExt, future::UnitError}; |
| 4 | +use futures::future::Executor as Executor01; |
| 5 | +use futures_core::task::Executor as Executor03; |
| 6 | +use futures_core::task as task03; |
| 7 | +use futures_core::future::FutureObj; |
| 8 | + |
| 9 | +pub struct BoxedExecutor03(Box<dyn Executor03 + Send>); |
| 10 | + |
| 11 | +impl Executor03 for BoxedExecutor03 { |
| 12 | + fn spawn_obj( |
| 13 | + &mut self, |
| 14 | + future: FutureObj<'static, ()>, |
| 15 | + ) -> Result<(), task03::SpawnObjError> { |
| 16 | + (&mut *self.0).spawn_obj(future) |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +/// A future that can run on a futures 0.1 executor. |
| 21 | +pub type Executor01Future = Compat<UnitError<FutureObj<'static, ()>>, BoxedExecutor03>; |
| 22 | + |
| 23 | +/// Extension trait for futures 0.1 Executors. |
| 24 | +pub trait Executor01CompatExt: Executor01<Executor01Future> + |
| 25 | + Clone + Send + 'static |
| 26 | +{ |
| 27 | + /// Creates an `Executor` compatable with futures 0.3. |
| 28 | + fn compat(self) -> Executor01As03<Self> |
| 29 | + where Self: Sized; |
| 30 | +} |
| 31 | + |
| 32 | +impl<Ex> Executor01CompatExt for Ex |
| 33 | +where Ex: Executor01<Executor01Future> + Clone + Send + 'static |
| 34 | +{ |
| 35 | + fn compat(self) -> Executor01As03<Self> { |
| 36 | + Executor01As03 { |
| 37 | + executor01: self, |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/// Converts a futures 0.1 `Executor` into a futures 0.3 `Executor`. |
| 43 | +#[derive(Clone)] |
| 44 | +pub struct Executor01As03<Ex> { |
| 45 | + executor01: Ex |
| 46 | +} |
| 47 | + |
| 48 | +impl<Ex> Executor03 for Executor01As03<Ex> |
| 49 | +where Ex: Executor01<Executor01Future>, |
| 50 | + Ex: Clone + Send + 'static, |
| 51 | +{ |
| 52 | + fn spawn_obj( |
| 53 | + &mut self, |
| 54 | + future: FutureObj<'static, ()>, |
| 55 | + ) -> Result<(), task03::SpawnObjError> { |
| 56 | + let future = future.unit_error().compat(BoxedExecutor03(Box::new(self.clone()))); |
| 57 | + |
| 58 | + match self.executor01.execute(future) { |
| 59 | + Ok(()) => Ok(()), |
| 60 | + Err(err) => { |
| 61 | + use futures_core::task::{SpawnObjError, SpawnErrorKind}; |
| 62 | + |
| 63 | + let fut = err.into_future().into_inner().unwrap_or_else(|_| ()); |
| 64 | + Err(SpawnObjError { |
| 65 | + kind: SpawnErrorKind::shutdown(), |
| 66 | + future: Box::new(fut).into(), |
| 67 | + }) |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments