future.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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) -> FnFuture<O>
  11. where
  12. T: Future<Output = O> + Send + Sync + 'static,
  13. {
  14. FnFuture { fut: Box::pin(f) }
  15. }
  16. #[pin_project]
  17. pub struct FnFuture<T> {
  18. #[pin]
  19. pub fut: Pin<Box<dyn Future<Output = T> + Sync + Send>>,
  20. }
  21. impl<T> Future for FnFuture<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>>;
  59. #[pin_project]
  60. pub struct FutureResultSend<T, E> {
  61. #[pin]
  62. pub fut: Pin<Box<dyn Future<Output = Result<T, E>> + Send>>,
  63. }
  64. impl<T, E> FutureResultSend<T, E> {
  65. pub fn new<F>(f: F) -> Self
  66. where
  67. F: Future<Output = Result<T, E>> + Send + 'static,
  68. {
  69. Self {
  70. fut: Box::pin(async { f.await }),
  71. }
  72. }
  73. }
  74. impl<T, E> Future for FutureResultSend<T, E>
  75. where
  76. T: Send,
  77. E: Debug,
  78. {
  79. type Output = Result<T, E>;
  80. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  81. let this = self.as_mut().project();
  82. let result = ready!(this.fut.poll(cx));
  83. Poll::Ready(result)
  84. }
  85. }