future.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use futures_core::future::BoxFuture;
  2. use futures_core::ready;
  3. use pin_project::pin_project;
  4. use std::{
  5. fmt::Debug,
  6. future::Future,
  7. pin::Pin,
  8. task::{Context, Poll},
  9. };
  10. pub fn to_fut<T, O>(f: T) -> Fut<O>
  11. where
  12. T: Future<Output = O> + Send + Sync + 'static,
  13. {
  14. Fut { fut: Box::pin(f) }
  15. }
  16. #[pin_project]
  17. pub struct Fut<T> {
  18. #[pin]
  19. pub fut: Pin<Box<dyn Future<Output = T> + Sync + Send>>,
  20. }
  21. impl<T> Future for Fut<T>
  22. where
  23. T: Send + Sync,
  24. {
  25. type Output = T;
  26. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  27. let this = self.as_mut().project();
  28. Poll::Ready(ready!(this.fut.poll(cx)))
  29. }
  30. }
  31. #[pin_project]
  32. pub struct FutureResult<T, E> {
  33. #[pin]
  34. pub fut: Pin<Box<dyn Future<Output = Result<T, E>> + Sync + Send>>,
  35. }
  36. impl<T, E> FutureResult<T, E> {
  37. pub fn new<F>(f: F) -> Self
  38. where
  39. F: Future<Output = Result<T, E>> + Send + Sync + 'static,
  40. {
  41. Self { fut: Box::pin(f) }
  42. }
  43. }
  44. impl<T, E> Future for FutureResult<T, E>
  45. where
  46. T: Send + Sync,
  47. E: Debug,
  48. {
  49. type Output = Result<T, E>;
  50. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  51. let this = self.as_mut().project();
  52. let result = ready!(this.fut.poll(cx));
  53. Poll::Ready(result)
  54. }
  55. }
  56. pub type BoxResultFuture<'a, T, E> = BoxFuture<'a, Result<T, E>>;