future.rs 1.4 KB

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