Struct wasi::io::streams::OutputStream

source ·
pub struct OutputStream { /* private fields */ }
Expand description

An output bytestream.

output-streams are non-blocking to the extent practical on underlying platforms. Except where specified otherwise, I/O operations also always return promptly, after the number of bytes that can be written promptly, which could even be zero. To wait for the stream to be ready to accept data, the subscribe function to obtain a pollable which can be polled for using wasi:io/poll.

Implementations§

source§

impl OutputStream

source

pub fn check_write(&self) -> Result<u64, StreamError>

Check readiness for writing. This function never blocks.

Returns the number of bytes permitted for the next call to write, or an error. Calling write with more bytes than this function has permitted will trap.

When this function returns 0 bytes, the subscribe pollable will become ready when this function will report at least 1 byte, or an error.

source§

impl OutputStream

source

pub fn write(&self, contents: &[u8]) -> Result<(), StreamError>

Perform a write. This function never blocks.

When the destination of a write is binary data, the bytes from contents are written verbatim. When the destination of a write is known to the implementation to be text, the bytes of contents are transcoded from UTF-8 into the encoding of the destination and then written.

Precondition: check-write gave permit of Ok(n) and contents has a length of less than or equal to n. Otherwise, this function will trap.

returns Err(closed) without writing if the stream has closed since the last call to check-write provided a permit.

source§

impl OutputStream

source

pub fn blocking_write_and_flush( &self, contents: &[u8] ) -> Result<(), StreamError>

Perform a write of up to 4096 bytes, and then flush the stream. Block until all of these operations are complete, or an error occurs.

This is a convenience wrapper around the use of check-write, subscribe, write, and flush, and is implemented with the following pseudo-code:

let pollable = this.subscribe();
while !contents.is_empty() {
// Wait for the stream to become writable
pollable.block();
let Ok(n) = this.check-write(); // eliding error handling
let len = min(n, contents.len());
let (chunk, rest) = contents.split_at(len);
this.write(chunk  );            // eliding error handling
contents = rest;
}
this.flush();
// Wait for completion of `flush`
pollable.block();
// Check for any errors that arose during `flush`
let _ = this.check-write();         // eliding error handling
Examples found in repository?
examples/hello-world-no_std.rs (line 3)
1
2
3
4
fn main() {
    let stdout = wasi::cli::stdout::get_stdout();
    stdout.blocking_write_and_flush(b"Hello, world!\n").unwrap();
}
More examples
Hide additional examples
examples/cli-command-no_std.rs (line 8)
6
7
8
9
10
    fn run() -> Result<(), ()> {
        let stdout = wasi::cli::stdout::get_stdout();
        stdout.blocking_write_and_flush(b"Hello, WASI!").unwrap();
        Ok(())
    }
examples/http-proxy-no_std.rs (line 17)
10
11
12
13
14
15
16
17
18
19
20
21
    fn handle(_request: IncomingRequest, response_out: ResponseOutparam) {
        let resp = OutgoingResponse::new(Fields::new());
        let body = resp.body().unwrap();

        ResponseOutparam::set(response_out, Ok(resp));

        let out = body.write().unwrap();
        out.blocking_write_and_flush(b"Hello, WASI!").unwrap();
        drop(out);

        OutgoingBody::finish(body, None).unwrap();
    }
source§

impl OutputStream

source

pub fn flush(&self) -> Result<(), StreamError>

Request to flush buffered output. This function never blocks.

This tells the output-stream that the caller intends any buffered output to be flushed. the output which is expected to be flushed is all that has been passed to write prior to this call.

Upon calling this function, the output-stream will not accept any writes (check-write will return ok(0)) until the flush has completed. The subscribe pollable will become ready when the flush has completed and the stream can accept more writes.

Examples found in repository?
examples/hello-world.rs (line 6)
3
4
5
6
7
fn main() {
    let mut stdout = wasi::cli::stdout::get_stdout();
    stdout.write_all(b"Hello, world!\n").unwrap();
    stdout.flush().unwrap();
}
More examples
Hide additional examples
examples/cli-command.rs (line 11)
8
9
10
11
12
13
    fn run() -> Result<(), ()> {
        let mut stdout = wasi::cli::stdout::get_stdout();
        stdout.write_all(b"Hello, WASI!").unwrap();
        stdout.flush().unwrap();
        Ok(())
    }
examples/http-proxy.rs (line 20)
12
13
14
15
16
17
18
19
20
21
22
23
24
    fn handle(_request: IncomingRequest, response_out: ResponseOutparam) {
        let resp = OutgoingResponse::new(Fields::new());
        let body = resp.body().unwrap();

        ResponseOutparam::set(response_out, Ok(resp));

        let mut out = body.write().unwrap();
        out.write_all(b"Hello, WASI!").unwrap();
        out.flush().unwrap();
        drop(out);

        OutgoingBody::finish(body, None).unwrap();
    }
source§

impl OutputStream

source

pub fn blocking_flush(&self) -> Result<(), StreamError>

Request to flush buffered output, and block until flush completes and stream is ready for writing again.

source§

impl OutputStream

source

pub fn subscribe(&self) -> Pollable

Create a pollable which will resolve once the output-stream is ready for more writing, or an error has occured. When this pollable is ready, check-write will return ok(n) with n>0, or an error.

If the stream is closed, this pollable is always ready immediately.

The created pollable is a child resource of the output-stream. Implementations may trap if the output-stream is dropped before all derived pollables created with this function are dropped.

source§

impl OutputStream

source

pub fn write_zeroes(&self, len: u64) -> Result<(), StreamError>

Write zeroes to a stream.

This should be used precisely like write with the exact same preconditions (must use check-write first), but instead of passing a list of bytes, you simply pass the number of zero-bytes that should be written.

source§

impl OutputStream

source

pub fn blocking_write_zeroes_and_flush( &self, len: u64 ) -> Result<(), StreamError>

Perform a write of up to 4096 zeroes, and then flush the stream. Block until all of these operations are complete, or an error occurs.

This is a convenience wrapper around the use of check-write, subscribe, write-zeroes, and flush, and is implemented with the following pseudo-code:

let pollable = this.subscribe();
while num_zeroes != 0 {
// Wait for the stream to become writable
pollable.block();
let Ok(n) = this.check-write(); // eliding error handling
let len = min(n, num_zeroes);
this.write-zeroes(len);         // eliding error handling
num_zeroes -= len;
}
this.flush();
// Wait for completion of `flush`
pollable.block();
// Check for any errors that arose during `flush`
let _ = this.check-write();         // eliding error handling
source§

impl OutputStream

source

pub fn splice(&self, src: &InputStream, len: u64) -> Result<u64, StreamError>

Read from one stream and write to another.

The behavior of splice is equivelant to:

  1. calling check-write on the output-stream
  2. calling read on the input-stream with the smaller of the check-write permitted length and the len provided to splice
  3. calling write on the output-stream with that read data.

Any error reported by the call to check-write, read, or write ends the splice and reports that error.

This function returns the number of bytes transferred; it may be less than len.

source§

impl OutputStream

source

pub fn blocking_splice( &self, src: &InputStream, len: u64 ) -> Result<u64, StreamError>

Read from one stream and write to another, with blocking.

This is similar to splice, except that it blocks until the output-stream is ready for writing, and the input-stream is ready for reading, before performing the splice.

Trait Implementations§

source§

impl Debug for OutputStream

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Write for OutputStream

source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Write a buffer into this writer, returning how many bytes were written. Read more
source§

fn flush(&mut self) -> Result<()>

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · source§

fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.