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
#![feature(waker_getters, provide_any)]
#![cfg_attr(not(feature = "std"), no_std)]
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg))]
mod demand;
mod provider;
mod waker;
pub use demand::{get_value, with_ref};
pub use provider::{ProvideRef, ProviderFut, ProviderFutExt};
pub use waker::ProviderWaker;
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub mod well_known;
#[cfg(test)]
mod tests {
use core::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use futures_util::FutureExt;
use super::*;
#[test]
fn ctx_with_ref() {
let val = async {
let upper = with_ref(|s: &str| s.to_uppercase()).await.unwrap();
let len = with_ref(|s: &str| s.len()).await.unwrap();
format!("{upper}{len}")
}
.provide_ref("foo")
.now_or_never()
.unwrap();
assert_eq!(val, "FOO3");
}
#[test]
fn ctx_get_value() {
let val = async {
let num1 = get_value::<i32>().await.unwrap();
let num2 = get_value::<i32>().await.unwrap();
num1 + num2
}
.provide_ref(&123)
.now_or_never()
.unwrap();
assert_eq!(val, 246);
}
#[tokio::test]
async fn waker_works() {
async {
yield_now().await;
yield_clone_now().await;
}
.provide_ref(&())
.await;
}
pub async fn yield_now() {
struct YieldNow {
yielded: bool,
}
impl Future for YieldNow {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
return Poll::Ready(());
}
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
YieldNow { yielded: false }.await
}
pub async fn yield_clone_now() {
struct YieldNow {
yielded: bool,
}
impl Future for YieldNow {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
return Poll::Ready(());
}
self.yielded = true;
cx.waker().clone().wake();
Poll::Pending
}
}
YieldNow { yielded: false }.await
}
}