Debian Codegraph @

third_party/rust/wit-bindgen-rt/src/async_support/future_support.rs

raw
1 extern crate std;
2
3 use {
4 super::Handle,
5 futures::{
6 channel::oneshot,
7 future::{self, FutureExt},
8 },
9 std::{
10 boxed::Box,
11 collections::hash_map::Entry,
12 fmt,
13 future::{Future, IntoFuture},
14 pin::Pin,
15 sync::atomic::{AtomicU32, Ordering::Relaxed},
16 task::{Context, Poll},
17 },
18 };
19
20 #[doc(hidden)]
21 pub struct FutureVtable<T> {
22 pub write: fn(future: u32, value: T) -> Pin<Box<dyn Future<Output = bool>>>,
23 pub read: fn(future: u32) -> Pin<Box<dyn Future<Output = Option<T>>>>,
24 pub cancel_write: fn(future: u32),
25 pub cancel_read: fn(future: u32),
26 pub close_writable: fn(future: u32),
27 pub close_readable: fn(future: u32),
28 }
29
30 /// Represents the writable end of a Component Model `future`.
31 pub struct FutureWriter<T: 'static> {
32 handle: u32,
33 vtable: &'static FutureVtable<T>,
34 }
35
36 impl<T> fmt::Debug for FutureWriter<T> {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 f.debug_struct("FutureWriter")
39 .field("handle", &self.handle)
40 .finish()
41 }
42 }
43
44 /// Represents a write operation which may be canceled prior to completion.
45 pub struct CancelableWrite<T: 'static> {
46 writer: Option<FutureWriter<T>>,
47 future: Pin<Box<dyn Future<Output = ()>>>,
48 }
49
50 impl<T> Future for CancelableWrite<T> {
51 type Output = ();
52
53 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
54 let me = self.get_mut();
55 match me.future.poll_unpin(cx) {
56 Poll::Ready(()) => {
57 me.writer = None;
58 Poll::Ready(())
59 }
60 Poll::Pending => Poll::Pending,
61 }
62 }
63 }
64
65 impl<T> CancelableWrite<T> {
66 /// Cancel this write if it hasn't already completed, returning the original `FutureWriter`.
67 ///
68 /// This method will panic if the write has already completed.
69 pub fn cancel(mut self) -> FutureWriter<T> {
70 self.cancel_mut()
71 }
72
73 fn cancel_mut(&mut self) -> FutureWriter<T> {
74 let writer = self.writer.take().unwrap();
75 super::with_entry(writer.handle, |entry| match entry {
76 Entry::Vacant(_) => unreachable!(),
77 Entry::Occupied(mut entry) => match entry.get() {
78 Handle::LocalOpen
79 | Handle::LocalWaiting(_)
80 | Handle::Read
81 | Handle::LocalClosed => unreachable!(),
82 Handle::LocalReady(..) => {
83 entry.insert(Handle::LocalOpen);
84 }
85 Handle::Write => (writer.vtable.cancel_write)(writer.handle),
86 },
87 });
88 writer
89 }
90 }
91
92 impl<T> Drop for CancelableWrite<T> {
93 fn drop(&mut self) {
94 if self.writer.is_some() {
95 self.cancel_mut();
96 }
97 }
98 }
99
100 impl<T> FutureWriter<T> {
101 #[doc(hidden)]
102 pub fn new(handle: u32, vtable: &'static FutureVtable<T>) -> Self {
103 Self { handle, vtable }
104 }
105
106 /// Write the specified value to this `future`.
107 pub fn write(self, v: T) -> CancelableWrite<T> {
108 let handle = self.handle;
109 let vtable = self.vtable;
110 CancelableWrite {
111 writer: Some(self),
112 future: super::with_entry(handle, |entry| match entry {
113 Entry::Vacant(_) => unreachable!(),
114 Entry::Occupied(mut entry) => match entry.get() {
115 Handle::LocalOpen => {
116 let mut v = Some(v);
117 Box::pin(future::poll_fn(move |cx| {
118 super::with_entry(handle, |entry| match entry {
119 Entry::Vacant(_) => unreachable!(),
120 Entry::Occupied(mut entry) => match entry.get() {
121 Handle::LocalOpen => {
122 entry.insert(Handle::LocalReady(
123 Box::new(v.take().unwrap()),
124 cx.waker().clone(),
125 ));
126 Poll::Pending
127 }
128 Handle::LocalReady(..) => Poll::Pending,
129 Handle::LocalClosed => Poll::Ready(()),
130 Handle::LocalWaiting(_) | Handle::Read | Handle::Write => {
131 unreachable!()
132 }
133 },
134 })
135 })) as Pin<Box<dyn Future<Output = _>>>
136 }
137 Handle::LocalWaiting(_) => {
138 let Handle::LocalWaiting(tx) = entry.insert(Handle::LocalClosed) else {
139 unreachable!()
140 };
141 _ = tx.send(Box::new(v));
142 Box::pin(future::ready(()))
143 }
144 Handle::LocalClosed => Box::pin(future::ready(())),
145 Handle::Read | Handle::LocalReady(..) => unreachable!(),
146 Handle::Write => Box::pin((vtable.write)(handle, v).map(drop)),
147 },
148 }),
149 }
150 }
151 }
152
153 impl<T> Drop for FutureWriter<T> {
154 fn drop(&mut self) {
155 super::with_entry(self.handle, |entry| match entry {
156 Entry::Vacant(_) => unreachable!(),
157 Entry::Occupied(mut entry) => match entry.get_mut() {
158 Handle::LocalOpen | Handle::LocalWaiting(_) | Handle::LocalReady(..) => {
159 entry.insert(Handle::LocalClosed);
160 }
161 Handle::Read => unreachable!(),
162 Handle::Write | Handle::LocalClosed => {
163 entry.remove();
164 (self.vtable.close_writable)(self.handle);
165 }
166 },
167 });
168 }
169 }
170
171 /// Represents a read operation which may be canceled prior to completion.
172 pub struct CancelableRead<T: 'static> {
173 reader: Option<FutureReader<T>>,
174 future: Pin<Box<dyn Future<Output = Option<T>>>>,
175 }
176
177 impl<T> Future for CancelableRead<T> {
178 type Output = Option<T>;
179
180 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<T>> {
181 let me = self.get_mut();
182 match me.future.poll_unpin(cx) {
183 Poll::Ready(v) => {
184 me.reader = None;
185 Poll::Ready(v)
186 }
187 Poll::Pending => Poll::Pending,
188 }
189 }
190 }
191
192 impl<T> CancelableRead<T> {
193 /// Cancel this read if it hasn't already completed, returning the original `FutureReader`.
194 ///
195 /// This method will panic if the read has already completed.
196 pub fn cancel(mut self) -> FutureReader<T> {
197 self.cancel_mut()
198 }
199
200 fn cancel_mut(&mut self) -> FutureReader<T> {
201 let reader = self.reader.take().unwrap();
202 let handle = reader.handle.load(Relaxed);
203 super::with_entry(handle, |entry| match entry {
204 Entry::Vacant(_) => unreachable!(),
205 Entry::Occupied(mut entry) => match entry.get() {
206 Handle::LocalOpen
207 | Handle::LocalReady(..)
208 | Handle::Write
209 | Handle::LocalClosed => unreachable!(),
210 Handle::LocalWaiting(_) => {
211 entry.insert(Handle::LocalOpen);
212 }
213 Handle::Read => (reader.vtable.cancel_read)(handle),
214 },
215 });
216 reader
217 }
218 }
219
220 impl<T> Drop for CancelableRead<T> {
221 fn drop(&mut self) {
222 if self.reader.is_some() {
223 self.cancel_mut();
224 }
225 }
226 }
227
228 /// Represents the readable end of a Component Model `future`.
229 pub struct FutureReader<T: 'static> {
230 handle: AtomicU32,
231 vtable: &'static FutureVtable<T>,
232 }
233
234 impl<T> fmt::Debug for FutureReader<T> {
235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 f.debug_struct("FutureReader")
237 .field("handle", &self.handle)
238 .finish()
239 }
240 }
241
242 impl<T> FutureReader<T> {
243 #[doc(hidden)]
244 pub fn new(handle: u32, vtable: &'static FutureVtable<T>) -> Self {
245 Self {
246 handle: AtomicU32::new(handle),
247 vtable,
248 }
249 }
250
251 #[doc(hidden)]
252 pub fn from_handle_and_vtable(handle: u32, vtable: &'static FutureVtable<T>) -> Self {
253 super::with_entry(handle, |entry| match entry {
254 Entry::Vacant(entry) => {
255 entry.insert(Handle::Read);
256 }
257 Entry::Occupied(mut entry) => match entry.get() {
258 Handle::Write => {
259 entry.insert(Handle::LocalOpen);
260 }
261 Handle::Read
262 | Handle::LocalOpen
263 | Handle::LocalReady(..)
264 | Handle::LocalWaiting(_)
265 | Handle::LocalClosed => {
266 unreachable!()
267 }
268 },
269 });
270
271 Self {
272 handle: AtomicU32::new(handle),
273 vtable,
274 }
275 }
276
277 #[doc(hidden)]
278 pub fn take_handle(&self) -> u32 {
279 let handle = self.handle.swap(u32::MAX, Relaxed);
280 super::with_entry(handle, |entry| match entry {
281 Entry::Vacant(_) => unreachable!(),
282 Entry::Occupied(mut entry) => match entry.get() {
283 Handle::LocalOpen => {
284 entry.insert(Handle::Write);
285 }
286 Handle::Read | Handle::LocalClosed => {
287 entry.remove();
288 }
289 Handle::LocalReady(..) | Handle::LocalWaiting(_) | Handle::Write => unreachable!(),
290 },
291 });
292
293 handle
294 }
295 }
296
297 impl<T> IntoFuture for FutureReader<T> {
298 type Output = Option<T>;
299 type IntoFuture = CancelableRead<T>;
300
301 /// Convert this object into a `Future` which will resolve when a value is
302 /// written to the writable end of this `future` (yielding a `Some` result)
303 /// or when the writable end is dropped (yielding a `None` result).
304 fn into_future(self) -> Self::IntoFuture {
305 let handle = self.handle.load(Relaxed);
306 let vtable = self.vtable;
307 CancelableRead {
308 reader: Some(self),
309 future: super::with_entry(handle, |entry| match entry {
310 Entry::Vacant(_) => unreachable!(),
311 Entry::Occupied(mut entry) => match entry.get() {
312 Handle::Write | Handle::LocalWaiting(_) => unreachable!(),
313 Handle::Read => Box::pin(async move { (vtable.read)(handle).await })
314 as Pin<Box<dyn Future<Output = _>>>,
315 Handle::LocalOpen => {
316 let (tx, rx) = oneshot::channel();
317 entry.insert(Handle::LocalWaiting(tx));
318 Box::pin(async move { rx.await.ok().map(|v| *v.downcast().unwrap()) })
319 }
320 Handle::LocalClosed => Box::pin(future::ready(None)),
321 Handle::LocalReady(..) => {
322 let Handle::LocalReady(v, waker) = entry.insert(Handle::LocalClosed) else {
323 unreachable!()
324 };
325 waker.wake();
326 Box::pin(future::ready(Some(*v.downcast().unwrap())))
327 }
328 },
329 }),
330 }
331 }
332 }
333
334 impl<T> Drop for FutureReader<T> {
335 fn drop(&mut self) {
336 match self.handle.load(Relaxed) {
337 u32::MAX => {}
338 handle => {
339 super::with_entry(handle, |entry| match entry {
340 Entry::Vacant(_) => unreachable!(),
341 Entry::Occupied(mut entry) => match entry.get_mut() {
342 Handle::LocalReady(..) => {
343 let Handle::LocalReady(_, waker) = entry.insert(Handle::LocalClosed)
344 else {
345 unreachable!()
346 };
347 waker.wake();
348 }
349 Handle::LocalOpen | Handle::LocalWaiting(_) => {
350 entry.insert(Handle::LocalClosed);
351 }
352 Handle::Read | Handle::LocalClosed => {
353 entry.remove();
354 (self.vtable.close_readable)(handle);
355 }
356 Handle::Write => unreachable!(),
357 },
358 });
359 }
360 }
361 }
362 }