use async_trait::async_trait;
use wasmtime::component::Resource;
use wasmtime_wasi::p2::{
DynInputStream, DynOutputStream, DynPollable, InputStream, OutputStream, Pollable, StreamError,
subscribe,
};
type StreamResult<T> = std::result::Result<T, StreamError>;
use bytes::Bytes;
struct AlwaysReadyPollable;
#[async_trait]
impl Pollable for AlwaysReadyPollable {
async fn ready(&mut self) {
}
}
pub(super) fn always_ready_pollable(
table: &mut wasmtime::component::ResourceTable,
) -> Resource<DynPollable> {
let stub = match table.push(AlwaysReadyPollable) {
Ok(r) => r,
Err(_) => return Resource::new_own(0),
};
subscribe(table, stub).unwrap_or_else(|_| Resource::new_own(0))
}
struct ClosedInputStream;
#[async_trait]
impl Pollable for ClosedInputStream {
async fn ready(&mut self) {
}
}
impl InputStream for ClosedInputStream {
fn read(&mut self, _size: usize) -> StreamResult<Bytes> {
Err(StreamError::Closed)
}
}
pub(super) fn closed_input_stream(
table: &mut wasmtime::component::ResourceTable,
) -> Resource<wasmtime_wasi::p2::bindings::sync::io::streams::InputStream> {
let boxed: DynInputStream = Box::new(ClosedInputStream);
let res = table.push(boxed).unwrap_or_else(|_| Resource::new_own(0));
Resource::new_own(res.rep())
}
struct ClosedOutputStream;
#[async_trait]
impl Pollable for ClosedOutputStream {
async fn ready(&mut self) {
}
}
#[async_trait]
impl OutputStream for ClosedOutputStream {
fn write(&mut self, _bytes: Bytes) -> StreamResult<()> {
Err(StreamError::Closed)
}
fn flush(&mut self) -> StreamResult<()> {
Err(StreamError::Closed)
}
fn check_write(&mut self) -> StreamResult<usize> {
Err(StreamError::Closed)
}
}
pub(super) fn closed_output_stream(
table: &mut wasmtime::component::ResourceTable,
) -> Resource<wasmtime_wasi::p2::bindings::sync::io::streams::OutputStream> {
let boxed: DynOutputStream = Box::new(ClosedOutputStream);
let res = table.push(boxed).unwrap_or_else(|_| Resource::new_own(0));
Resource::new_own(res.rep())
}