1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#![deny(missing_docs)]
#![deny(unused_must_use)]
use futures::future::BoxFuture;
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct MustFuture<F: std::future::Future> {
sub_fut: F,
}
impl<F: std::future::Future> MustFuture<F> {
pin_utils::unsafe_pinned!(sub_fut: F);
}
impl<F: std::future::Future> From<F> for MustFuture<F> {
fn from(f: F) -> Self {
Self { sub_fut: f }
}
}
impl<F: std::future::Future> std::future::Future for MustFuture<F> {
type Output = F::Output;
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context,
) -> std::task::Poll<Self::Output> {
let p: std::pin::Pin<&mut F> = self.sub_fut();
std::future::Future::poll(p, cx)
}
}
impl<F: std::future::Future + std::marker::Unpin> std::marker::Unpin for MustFuture<F> {}
impl<F: std::future::Future> std::fmt::Debug for MustFuture<F> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MustFuture").finish()
}
}
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct MustBoxFuture<'lt, T> {
sub_fut: BoxFuture<'lt, T>,
}
impl<'lt, T> From<BoxFuture<'lt, T>> for MustBoxFuture<'lt, T> {
fn from(f: BoxFuture<'lt, T>) -> Self {
Self { sub_fut: f }
}
}
impl<'lt, T> std::future::Future for MustBoxFuture<'lt, T> {
type Output = T;
fn poll(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context,
) -> std::task::Poll<Self::Output> {
std::future::Future::poll(self.sub_fut.as_mut(), cx)
}
}
impl<'lt, T> std::fmt::Debug for MustBoxFuture<'lt, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MustBoxFuture").finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::future::FutureExt;
#[tokio::test]
pub async fn must_box_future_is_debug() {
fn get_future() -> MustBoxFuture<'static, &'static str> {
async { "test1" }.boxed().into()
}
assert_eq!("MustBoxFuture", &format!("{:?}", get_future()));
}
#[tokio::test]
pub async fn must_box_future_can_still_process() {
fn get_future() -> MustBoxFuture<'static, &'static str> {
async { "test1" }.boxed().into()
}
assert_eq!("test1", get_future().await);
}
#[tokio::test]
pub async fn must_future_is_debug() {
fn get_future() -> MustFuture<BoxFuture<'static, &'static str>> {
async { "test2" }.boxed().into()
}
assert_eq!("MustFuture", &format!("{:?}", get_future()));
}
#[tokio::test]
pub async fn must_future_can_still_process() {
fn get_future() -> MustFuture<BoxFuture<'static, &'static str>> {
async { "test2" }.boxed().into()
}
assert_eq!("test2", get_future().await);
}
}