future.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 wrap_future<T, O>(f: T) -> AFFuture<O>
  11. where
  12. T: Future<Output = O> + Send + Sync + 'static,
  13. {
  14. AFFuture { fut: Box::pin(f) }
  15. }
  16. #[pin_project]
  17. pub struct AFFuture<T> {
  18. #[pin]
  19. pub fut: Pin<Box<dyn Future<Output = T> + Sync + Send>>,
  20. }
  21. impl<T> Future for AFFuture<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 {
  42. fut: Box::pin(async { f.await }),
  43. }
  44. }
  45. }
  46. impl<T, E> Future for FutureResult<T, E>
  47. where
  48. T: Send + Sync,
  49. E: Debug,
  50. {
  51. type Output = Result<T, E>;
  52. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  53. let this = self.as_mut().project();
  54. let result = ready!(this.fut.poll(cx));
  55. Poll::Ready(result)
  56. }
  57. }
  58. pub type BoxResultFuture<'a, T, E> = BoxFuture<'a, Result<T, E>>;