Debian Codegraph @

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

raw
1 extern crate std;
2
3 use {
4 super::Handle,
5 futures::{
6 channel::oneshot,
7 future::{self, FutureExt},
8 sink::Sink,
9 stream::Stream,
10 },
11 std::{
12 boxed::Box,
13 collections::hash_map::Entry,
14 convert::Infallible,
15 fmt,
16 future::Future,
17 iter,
18 mem::{self, MaybeUninit},
19 pin::Pin,
20 sync::atomic::{AtomicU32, Ordering::Relaxed},
21 task::{Context, Poll},
22 vec::Vec,
23 },
24 };
25
26 fn ceiling(x: usize, y: usize) -> usize {
27 (x / y) + if x % y == 0 { 0 } else { 1 }
28 }
29
30 #[doc(hidden)]
31 pub struct StreamVtable<T> {
32 pub write: fn(future: u32, values: &[T]) -> Pin<Box<dyn Future<Output = usize> + '_>>,
33 pub read: fn(
34 future: u32,
35 values: &mut [MaybeUninit<T>],
36 ) -> Pin<Box<dyn Future<Output = Option<usize>> + '_>>,
37 pub cancel_write: fn(future: u32),
38 pub cancel_read: fn(future: u32),
39 pub close_writable: fn(future: u32),
40 pub close_readable: fn(future: u32),
41 }
42
43 struct CancelWriteOnDrop<T: 'static> {
44 handle: Option<u32>,
45 vtable: &'static StreamVtable<T>,
46 }
47
48 impl<T> Drop for CancelWriteOnDrop<T> {
49 fn drop(&mut self) {
50 if let Some(handle) = self.handle.take() {
51 super::with_entry(handle, |entry| match entry {
52 Entry::Vacant(_) => unreachable!(),
53 Entry::Occupied(mut entry) => match entry.get() {
54 Handle::LocalOpen
55 | Handle::LocalWaiting(_)
56 | Handle::Read
57 | Handle::LocalClosed => unreachable!(),
58 Handle::LocalReady(..) => {
59 entry.insert(Handle::LocalOpen);
60 }
61 Handle::Write => (self.vtable.cancel_write)(handle),
62 },
63 });
64 }
65 }
66 }
67
68 /// Represents the writable end of a Component Model `stream`.
69 pub struct StreamWriter<T: 'static> {
70 handle: u32,
71 future: Option<Pin<Box<dyn Future<Output = ()> + 'static>>>,
72 vtable: &'static StreamVtable<T>,
73 }
74
75 impl<T> StreamWriter<T> {
76 #[doc(hidden)]
77 pub fn new(handle: u32, vtable: &'static StreamVtable<T>) -> Self {
78 Self {
79 handle,
80 future: None,
81 vtable,
82 }
83 }
84
85 /// Cancel the current pending write operation.
86 ///
87 /// This will panic if no such operation is pending.
88 pub fn cancel(&mut self) {
89 assert!(self.future.is_some());
90 self.future = None;
91 }
92 }
93
94 impl<T> fmt::Debug for StreamWriter<T> {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 f.debug_struct("StreamWriter")
97 .field("handle", &self.handle)
98 .finish()
99 }
100 }
101
102 impl<T> Sink<Vec<T>> for StreamWriter<T> {
103 type Error = Infallible;
104
105 fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
106 let me = self.get_mut();
107
108 if let Some(future) = &mut me.future {
109 match future.as_mut().poll(cx) {
110 Poll::Ready(_) => {
111 me.future = None;
112 Poll::Ready(Ok(()))
113 }
114 Poll::Pending => Poll::Pending,
115 }
116 } else {
117 Poll::Ready(Ok(()))
118 }
119 }
120
121 fn start_send(self: Pin<&mut Self>, item: Vec<T>) -> Result<(), Self::Error> {
122 assert!(self.future.is_none());
123 super::with_entry(self.handle, |entry| match entry {
124 Entry::Vacant(_) => unreachable!(),
125 Entry::Occupied(mut entry) => match entry.get() {
126 Handle::LocalOpen => {
127 let handle = self.handle;
128 let mut item = Some(item);
129 let mut cancel_on_drop = Some(CancelWriteOnDrop::<T> {
130 handle: Some(handle),
131 vtable: self.vtable,
132 });
133 self.get_mut().future = Some(Box::pin(future::poll_fn(move |cx| {
134 super::with_entry(handle, |entry| match entry {
135 Entry::Vacant(_) => unreachable!(),
136 Entry::Occupied(mut entry) => match entry.get() {
137 Handle::LocalOpen => {
138 if let Some(item) = item.take() {
139 entry.insert(Handle::LocalReady(
140 Box::new(item),
141 cx.waker().clone(),
142 ));
143 Poll::Pending
144 } else {
145 cancel_on_drop.take().unwrap().handle = None;
146 Poll::Ready(())
147 }
148 }
149 Handle::LocalReady(..) => Poll::Pending,
150 Handle::LocalClosed => {
151 cancel_on_drop.take().unwrap().handle = None;
152 Poll::Ready(())
153 }
154 Handle::LocalWaiting(_) | Handle::Read | Handle::Write => {
155 unreachable!()
156 }
157 },
158 })
159 })));
160 }
161 Handle::LocalWaiting(_) => {
162 let Handle::LocalWaiting(tx) = entry.insert(Handle::LocalOpen) else {
163 unreachable!()
164 };
165 _ = tx.send(Box::new(item));
166 }
167 Handle::LocalClosed => (),
168 Handle::Read | Handle::LocalReady(..) => unreachable!(),
169 Handle::Write => {
170 let handle = self.handle;
171 let vtable = self.vtable;
172 let mut cancel_on_drop = CancelWriteOnDrop::<T> {
173 handle: Some(handle),
174 vtable,
175 };
176 self.get_mut().future = Some(Box::pin(async move {
177 (vtable.write)(handle, &item).await;
178 cancel_on_drop.handle = None;
179 drop(cancel_on_drop);
180 }));
181 }
182 },
183 });
184 Ok(())
185 }
186
187 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
188 self.poll_ready(cx)
189 }
190
191 fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
192 self.poll_ready(cx)
193 }
194 }
195
196 impl<T> Drop for StreamWriter<T> {
197 fn drop(&mut self) {
198 self.future = None;
199
200 super::with_entry(self.handle, |entry| match entry {
201 Entry::Vacant(_) => unreachable!(),
202 Entry::Occupied(mut entry) => match entry.get_mut() {
203 Handle::LocalOpen | Handle::LocalWaiting(_) | Handle::LocalReady(..) => {
204 entry.insert(Handle::LocalClosed);
205 }
206 Handle::Read => unreachable!(),
207 Handle::Write | Handle::LocalClosed => {
208 entry.remove();
209 (self.vtable.close_writable)(self.handle);
210 }
211 },
212 });
213 }
214 }
215
216 struct CancelReadOnDrop<T: 'static> {
217 handle: Option<u32>,
218 vtable: &'static StreamVtable<T>,
219 }
220
221 impl<T> Drop for CancelReadOnDrop<T> {
222 fn drop(&mut self) {
223 if let Some(handle) = self.handle.take() {
224 super::with_entry(handle, |entry| match entry {
225 Entry::Vacant(_) => unreachable!(),
226 Entry::Occupied(mut entry) => match entry.get() {
227 Handle::LocalOpen
228 | Handle::LocalReady(..)
229 | Handle::Write
230 | Handle::LocalClosed => unreachable!(),
231 Handle::LocalWaiting(_) => {
232 entry.insert(Handle::LocalOpen);
233 }
234 Handle::Read => (self.vtable.cancel_read)(handle),
235 },
236 });
237 }
238 }
239 }
240
241 /// Represents the readable end of a Component Model `stream`.
242 pub struct StreamReader<T: 'static> {
243 handle: AtomicU32,
244 future: Option<Pin<Box<dyn Future<Output = Option<Vec<T>>> + 'static>>>,
245 vtable: &'static StreamVtable<T>,
246 }
247
248 impl<T> StreamReader<T> {
249 /// Cancel the current pending read operation.
250 ///
251 /// This will panic if no such operation is pending.
252 pub fn cancel(&mut self) {
253 assert!(self.future.is_some());
254 self.future = None;
255 }
256 }
257
258 impl<T> fmt::Debug for StreamReader<T> {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260 f.debug_struct("StreamReader")
261 .field("handle", &self.handle)
262 .finish()
263 }
264 }
265
266 impl<T> StreamReader<T> {
267 #[doc(hidden)]
268 pub fn new(handle: u32, vtable: &'static StreamVtable<T>) -> Self {
269 Self {
270 handle: AtomicU32::new(handle),
271 future: None,
272 vtable,
273 }
274 }
275
276 #[doc(hidden)]
277 pub fn from_handle_and_vtable(handle: u32, vtable: &'static StreamVtable<T>) -> Self {
278 super::with_entry(handle, |entry| match entry {
279 Entry::Vacant(entry) => {
280 entry.insert(Handle::Read);
281 }
282 Entry::Occupied(mut entry) => match entry.get() {
283 Handle::Write => {
284 entry.insert(Handle::LocalOpen);
285 }
286 Handle::Read
287 | Handle::LocalOpen
288 | Handle::LocalReady(..)
289 | Handle::LocalWaiting(_)
290 | Handle::LocalClosed => {
291 unreachable!()
292 }
293 },
294 });
295
296 Self {
297 handle: AtomicU32::new(handle),
298 future: None,
299 vtable,
300 }
301 }
302
303 #[doc(hidden)]
304 pub fn take_handle(&self) -> u32 {
305 let handle = self.handle.swap(u32::MAX, Relaxed);
306 super::with_entry(handle, |entry| match entry {
307 Entry::Vacant(_) => unreachable!(),
308 Entry::Occupied(mut entry) => match entry.get() {
309 Handle::LocalOpen => {
310 entry.insert(Handle::Write);
311 }
312 Handle::Read | Handle::LocalClosed => {
313 entry.remove();
314 }
315 Handle::LocalReady(..) | Handle::LocalWaiting(_) | Handle::Write => unreachable!(),
316 },
317 });
318
319 handle
320 }
321 }
322
323 impl<T> Stream for StreamReader<T> {
324 type Item = Vec<T>;
325
326 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
327 let me = self.get_mut();
328
329 if me.future.is_none() {
330 me.future = Some(super::with_entry(
331 me.handle.load(Relaxed),
332 |entry| match entry {
333 Entry::Vacant(_) => unreachable!(),
334 Entry::Occupied(mut entry) => match entry.get() {
335 Handle::Write | Handle::LocalWaiting(_) => unreachable!(),
336 Handle::Read => {
337 let handle = me.handle.load(Relaxed);
338 let vtable = me.vtable;
339 let mut cancel_on_drop = CancelReadOnDrop::<T> {
340 handle: Some(handle),
341 vtable,
342 };
343 Box::pin(async move {
344 let mut buffer = iter::repeat_with(MaybeUninit::uninit)
345 .take(ceiling(64 * 1024, mem::size_of::<T>().max(1)))
346 .collect::<Vec<_>>();
347
348 let result =
349 if let Some(count) = (vtable.read)(handle, &mut buffer).await {
350 buffer.truncate(count);
351 Some(unsafe {
352 mem::transmute::<Vec<MaybeUninit<T>>, Vec<T>>(buffer)
353 })
354 } else {
355 None
356 };
357 cancel_on_drop.handle = None;
358 drop(cancel_on_drop);
359 result
360 }) as Pin<Box<dyn Future<Output = _>>>
361 }
362 Handle::LocalOpen => {
363 let (tx, rx) = oneshot::channel();
364 entry.insert(Handle::LocalWaiting(tx));
365 let mut cancel_on_drop = CancelReadOnDrop::<T> {
366 handle: Some(me.handle.load(Relaxed)),
367 vtable: me.vtable,
368 };
369 Box::pin(async move {
370 let result =
371 rx.map(|v| v.ok().map(|v| *v.downcast().unwrap())).await;
372 cancel_on_drop.handle = None;
373 drop(cancel_on_drop);
374 result
375 })
376 }
377 Handle::LocalClosed => Box::pin(future::ready(None)),
378 Handle::LocalReady(..) => {
379 let Handle::LocalReady(v, waker) = entry.insert(Handle::LocalOpen)
380 else {
381 unreachable!()
382 };
383 waker.wake();
384 Box::pin(future::ready(Some(*v.downcast().unwrap())))
385 }
386 },
387 },
388 ));
389 }
390
391 match me.future.as_mut().unwrap().as_mut().poll(cx) {
392 Poll::Ready(v) => {
393 me.future = None;
394 Poll::Ready(v)
395 }
396 Poll::Pending => Poll::Pending,
397 }
398 }
399 }
400
401 impl<T> Drop for StreamReader<T> {
402 fn drop(&mut self) {
403 self.future = None;
404
405 match self.handle.load(Relaxed) {
406 u32::MAX => {}
407 handle => {
408 super::with_entry(handle, |entry| match entry {
409 Entry::Vacant(_) => unreachable!(),
410 Entry::Occupied(mut entry) => match entry.get_mut() {
411 Handle::LocalReady(..) => {
412 let Handle::LocalReady(_, waker) = entry.insert(Handle::LocalClosed)
413 else {
414 unreachable!()
415 };
416 waker.wake();
417 }
418 Handle::LocalOpen | Handle::LocalWaiting(_) => {
419 entry.insert(Handle::LocalClosed);
420 }
421 Handle::Read | Handle::LocalClosed => {
422 entry.remove();
423 (self.vtable.close_readable)(handle);
424 }
425 Handle::Write => unreachable!(),
426 },
427 });
428 }
429 }
430 }
431 }