future.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. use futures_core::{future::BoxFuture, 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. Poll::Ready(ready!(this.fut.poll(cx)))
  28. }
  29. }
  30. #[pin_project]
  31. pub struct FutureResult<T, E> {
  32. #[pin]
  33. pub fut: Pin<Box<dyn Future<Output = Result<T, E>> + Sync + Send>>,
  34. }
  35. impl<T, E> FutureResult<T, E> {
  36. pub fn new<F>(f: F) -> Self
  37. where
  38. F: Future<Output = Result<T, E>> + Send + Sync + 'static,
  39. {
  40. Self {
  41. fut: Box::pin(async { f.await }),
  42. }
  43. }
  44. }
  45. impl<T, E> Future for FutureResult<T, E>
  46. where
  47. T: Send + Sync,
  48. E: Debug,
  49. {
  50. type Output = Result<T, E>;
  51. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  52. let this = self.as_mut().project();
  53. let result = ready!(this.fut.poll(cx));
  54. Poll::Ready(result)
  55. }
  56. }
  57. pub type BoxResultFuture<'a, T, E> = BoxFuture<'a, Result<T, E>>;
  58. #[pin_project]
  59. pub struct FutureResultSend<T, E> {
  60. #[pin]
  61. pub fut: Pin<Box<dyn Future<Output = Result<T, E>> + Send>>,
  62. }
  63. impl<T, E> FutureResultSend<T, E> {
  64. pub fn new<F>(f: F) -> Self
  65. where
  66. F: Future<Output = Result<T, E>> + Send + 'static,
  67. {
  68. Self {
  69. fut: Box::pin(async { f.await }),
  70. }
  71. }
  72. }
  73. impl<T, E> Future for FutureResultSend<T, E>
  74. where
  75. T: Send,
  76. E: Debug,
  77. {
  78. type Output = Result<T, E>;
  79. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  80. let this = self.as_mut().project();
  81. let result = ready!(this.fut.poll(cx));
  82. Poll::Ready(result)
  83. }
  84. }