Skip to content
This repository was archived by the owner on Sep 8, 2025. It is now read-only.

Commit a71108f

Browse files
authored
Add InputFile for use with WasiCtxBuilder (#10968)
1 parent d282544 commit a71108f

2 files changed

Lines changed: 55 additions & 2 deletions

File tree

crates/wasi/src/p2/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,8 +246,8 @@ pub use self::ctx::{WasiCtx, WasiCtxBuilder};
246246
pub use self::filesystem::{FsError, FsResult};
247247
pub use self::network::{SocketError, SocketResult};
248248
pub use self::stdio::{
249-
AsyncStdinStream, AsyncStdoutStream, IsATTY, OutputFile, Stderr, Stdin, StdinStream, Stdout,
250-
StdoutStream, stderr, stdin, stdout,
249+
AsyncStdinStream, AsyncStdoutStream, InputFile, IsATTY, OutputFile, Stderr, Stdin, StdinStream,
250+
Stdout, StdoutStream, stderr, stdin, stdout,
251251
};
252252
pub use self::view::{WasiImpl, WasiView};
253253
// These contents of wasmtime-wasi-io are re-exported by this module for compatibility:

crates/wasi/src/p2/stdio.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,59 @@ impl StdinStream for pipe::ClosedInputStream {
5858
}
5959
}
6060

61+
/// This implementation will yield input streams that block on reads, and
62+
/// reads directly from a file. If truly async input is required,
63+
/// [`AsyncStdinStream`] should be used instead.
64+
pub struct InputFile {
65+
file: Arc<std::fs::File>,
66+
}
67+
68+
impl InputFile {
69+
pub fn new(file: std::fs::File) -> Self {
70+
Self {
71+
file: Arc::new(file),
72+
}
73+
}
74+
}
75+
76+
impl StdinStream for InputFile {
77+
fn stream(&self) -> Box<dyn InputStream> {
78+
Box::new(InputFileStream {
79+
file: Arc::clone(&self.file),
80+
})
81+
}
82+
83+
fn isatty(&self) -> bool {
84+
false
85+
}
86+
}
87+
88+
struct InputFileStream {
89+
file: Arc<std::fs::File>,
90+
}
91+
92+
#[async_trait::async_trait]
93+
impl Pollable for InputFileStream {
94+
async fn ready(&mut self) {}
95+
}
96+
97+
impl InputStream for InputFileStream {
98+
fn read(&mut self, size: usize) -> StreamResult<Bytes> {
99+
use std::io::Read;
100+
101+
let mut buf = bytes::BytesMut::zeroed(size);
102+
let bytes_read = self
103+
.file
104+
.read(&mut buf)
105+
.map_err(|e| StreamError::LastOperationFailed(anyhow::anyhow!(e)))?;
106+
if bytes_read == 0 {
107+
return Err(StreamError::Closed);
108+
}
109+
buf.truncate(bytes_read);
110+
StreamResult::Ok(buf.into())
111+
}
112+
}
113+
61114
/// An impl of [`StdinStream`] built on top of [`crate::p2::pipe::AsyncReadStream`].
62115
//
63116
// Note the usage of `tokio::sync::Mutex` here as opposed to a

0 commit comments

Comments
 (0)