1 use {
2 bindings::{
3 exports::local::local::short_reads::{self, Guest, GuestThing},
4 wit_stream,
5 },
6 wit_bindgen::{StreamReader, StreamResult, rt::async_support},
7 };
8
9 mod bindings {
10 wit_bindgen::generate!({
11 path: "../misc/component-async-tests/wit",
12 world: "short-reads-guest",
13 });
14
15 use super::Component;
16 export!(Component);
17 }
18
19 struct Thing {
20 value: String,
21 }
22
23 impl GuestThing for Thing {
new(value: String) -> Self24 fn new(value: String) -> Self {
25 Self { value }
26 }
27
get(&self) -> String28 async fn get(&self) -> String {
29 self.value.clone()
30 }
31 }
32
33 struct Component;
34
35 impl Guest for Component {
36 type Thing = Thing;
37
short_reads( mut stream: StreamReader<short_reads::Thing>, ) -> StreamReader<short_reads::Thing>38 async fn short_reads(
39 mut stream: StreamReader<short_reads::Thing>,
40 ) -> StreamReader<short_reads::Thing> {
41 let (mut tx, rx) = wit_stream::new();
42
43 async_support::spawn(async move {
44 // Read the things one at a time, forcing the host to re-take
45 // ownership of any unwritten items between writes.
46 let mut things = Vec::new();
47 loop {
48 let (status, buffer) = stream.read(Vec::with_capacity(1)).await;
49 match status {
50 StreamResult::Complete(_) => {
51 things.extend(buffer);
52 }
53 StreamResult::Dropped => break,
54 StreamResult::Cancelled => unreachable!(),
55 }
56 }
57 // Write the things all at once. The host will read them only one
58 // at a time, forcing us to re-take ownership of any unwritten
59 // items between writes.
60 things = tx.write_all(things).await;
61 assert!(things.is_empty());
62 });
63
64 rx
65 }
66 }
67
68 // Unused function; required since this file is built as a `bin`:
main()69 fn main() {}
70