Path: blob/main/crates/test-programs/src/bin/async_short_reads.rs
3069 views
use {1bindings::{2exports::local::local::short_reads::{self, Guest, GuestThing},3wit_stream,4},5wit_bindgen::{StreamReader, StreamResult, rt::async_support},6};78mod bindings {9wit_bindgen::generate!({10path: "../misc/component-async-tests/wit",11world: "short-reads-guest",12});1314use super::Component;15export!(Component);16}1718struct Thing {19value: String,20}2122impl GuestThing for Thing {23fn new(value: String) -> Self {24Self { value }25}2627async fn get(&self) -> String {28self.value.clone()29}30}3132struct Component;3334impl Guest for Component {35type Thing = Thing;3637async fn short_reads(38mut stream: StreamReader<short_reads::Thing>,39) -> StreamReader<short_reads::Thing> {40let (mut tx, rx) = wit_stream::new();4142async_support::spawn(async move {43// Read the things one at a time, forcing the host to re-take44// ownership of any unwritten items between writes.45let mut things = Vec::new();46loop {47let (status, buffer) = stream.read(Vec::with_capacity(1)).await;48match status {49StreamResult::Complete(_) => {50things.extend(buffer);51}52StreamResult::Dropped => break,53StreamResult::Cancelled => unreachable!(),54}55}56// Write the things all at once. The host will read them only one57// at a time, forcing us to re-take ownership of any unwritten58// items between writes.59things = tx.write_all(things).await;60assert!(things.is_empty());61});6263rx64}65}6667// Unused function; required since this file is built as a `bin`:68fn main() {}697071