future.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #[pin_project]
  10. pub struct RequestFuture<T> {
  11. #[pin]
  12. pub fut: Pin<Box<dyn Future<Output = T> + Sync + Send>>,
  13. }
  14. impl<T> Future for RequestFuture<T>
  15. where
  16. T: Send + Sync,
  17. {
  18. type Output = T;
  19. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  20. let this = self.as_mut().project();
  21. loop {
  22. return Poll::Ready(ready!(this.fut.poll(cx)));
  23. }
  24. }
  25. }
  26. #[pin_project]
  27. pub struct ResultFuture<T, E> {
  28. #[pin]
  29. pub fut: Pin<Box<dyn Future<Output = Result<T, E>> + Sync + Send>>,
  30. }
  31. impl<T, E> ResultFuture<T, E> {
  32. pub fn new<F>(f: F) -> Self
  33. where
  34. F: Future<Output = Result<T, E>> + Send + Sync + 'static,
  35. {
  36. Self {
  37. fut: Box::pin(async { f.await }),
  38. }
  39. }
  40. }
  41. impl<T, E> Future for ResultFuture<T, E>
  42. where
  43. T: Send + Sync,
  44. E: Debug,
  45. {
  46. type Output = Result<T, E>;
  47. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  48. let this = self.as_mut().project();
  49. loop {
  50. let result = ready!(this.fut.poll(cx));
  51. return Poll::Ready(result);
  52. }
  53. }
  54. }