docs

您正在閱讀 v0.1.0 的文件。Nabi 0.1.0 已停止支援。 最新版本:v0.1.3 →

本頁尚未翻譯,以下為英文原文。

#2.23. io:: - byte streams and standard I/O

本頁內容

core::io holds all of Nabi's I/O vocabulary: the error type, the stream traits Read, BufRead, Write and Seek with their async twins AsyncRead, AsyncBufRead, AsyncWrite and AsyncSeek, Close and AsyncClose, the buffers, Cursor, copy and the standard streams. The types that reach the OS (File, sockets, TLS connections, child pipes) live in std and implement these traits; everything here is target-independent, and the standard streams exist on every target (in the browser stdout / stderr go to the host console and stdin is at its end, 0.1.4).

The prelude names the module io and the traits Read, Write, AsyncRead and AsyncWrite, so io::stdin(), io::BufReader::new(f) and f.read(buf) need no use. BufRead, Seek, AsyncBufRead and AsyncSeek are written io::BufRead and so on in bounds; their methods resolve without an import. There is no std::io.

Every stream method has one definition: File, TcpStream, UnixStream, tls::Client and tls::Server have no inherent read / write / read_to_end / flush or _async twins of them; the calls resolve through the traits.

#2.23.0. IoError

kind() comes from the OS error code (UnexpectedEof, InvalidData and WriteZero are set by the library); the code itself is os_code() and the OS description (the runtime's strerror) is message(). os_code() is none for an error the library raises itself (IoError::new(InvalidInput, "..")) and for a name that does not resolve (3.2.4): a resolver (EAI) code is not an OS error code. Such a lookup failure keeps the resolver's message and is NotFound when the name does not exist, Other otherwise. On Windows a lookup fails with a Winsock code, which os_code() returns. IoErrorKind is #[non_exhaustive]: a match outside core needs a _ arm.

last_os_error() is from_os_code of the code the last #[errno] C call on this thread saved (stdlib 1.7.11): on Windows its GetLastError when that is nonzero, else its errno; elsewhere its errno. A call declared without #[errno] saves nothing, so the code is an older call's.

#2.23.1. Read

nabi
trait Read {
    fn read(ref self, buf: SliceMut<u8>) throws (IoError) -> usize;  // fills buf[0..n]; 0 = end (or an empty buf)

    // low level
    fn read_vectored(ref self, bufs: Slice<SliceMut<u8>>) throws (IoError) -> usize;  // default: the first non-empty buffer
    fn read_exact(ref self, buf: SliceMut<u8>) throws (IoError);                      // all of buf, or UnexpectedEof
    fn read_to_end_into(ref self, out: List<u8>) throws (IoError) -> usize;           // appends the rest; the count

    // convenient
    fn read_to_end(ref self) throws (IoError) -> List<u8>;
    fn read_to_str(ref self) throws (IoError) -> str;           // InvalidData if not UTF-8
    fn bytes(ref self) -> Bytes<Self>;                          // view; TryIterator<Item = u8, Error = IoError>
    fn take(ref self, limit: u64) -> Take<Self>;                // view; at most limit bytes
    fn chain<R: Read>(self, next: R) -> Chain<Self, R>;         // owns both: this stream, then next

    // owning forms
    fn into_bytes(self) -> Owned<Bytes<Self>, Self>;
    fn into_take(self, limit: u64) -> Owned<Take<Self>, Self>;
}

read is the one required method. A buffer is a SliceMut<u8> (2.9): a List<u8> passes as a view of the whole list, and buf[a:b] reads into part of it. read_to_end_into reads into the list's spare capacity with no zero fill first: the exact low-level form of read_to_end.

bytes and take (and lines, split, bytes_async, lines_async and TcpListener::incoming) return a scoped view of the stream: the adapter reads through the stream, which keeps its one owner (2.13.4), and the owner still closes it. A view stays in the scope of the stream's owner, like a lock guard's value (2.16.3): returning it, storing it past that scope, passing it to a callee that keeps it, or using it after the stream was closed or moved is compile error E0139. A call that only reads the stream lends it (r.capacity(), f"{r:?}", a by-value parameter the callee does not keep, as in 2.13.4), and its views go on. Views are neither Send nor Sync, so a task cannot capture one. A helper that takes the stream as ref r may return a view of it: the view is then tied to the caller's stream.

The into_ forms are the owning adapters: r.into_lines() takes r and returns an Owned<V, R> that iterates (reads, streams) as the view V does, closes r with itself (Close / AsyncClose) and gives it back with into_inner(). Use the view inside the owner's scope (using r = .. { try for l in r.lines() { .. } }); use the owning form when the adapter must leave the scope: returned from a function, kept in a struct, or moved into a task. chain always owns both streams: it closes both and into_inner() returns the pair. bytes costs one read per byte; wrap an unbuffered stream in BufReader first.

#2.23.2. BufRead

nabi
trait BufRead: Read {
    // low level
    fn fill_buf(ref self) throws (IoError) -> Slice<u8>;    // the buffered bytes, refilled when empty; empty = end
    fn consume(ref self, n: usize);                         // mark n buffered bytes read; panics past them (`BufReader::consume: ..`)
    fn read_until(ref self, delim: u8, out: List<u8>) throws (IoError) -> usize;  // appends through delim; 0 = end
    fn read_line(ref self, out: StrBuf) throws (IoError) -> usize;                // appends a line with its \n; 0 = end
    fn skip_until(ref self, delim: u8) throws (IoError) -> usize;

    // convenient
    fn lines(ref self) -> Lines<Self>;                  // view; TryIterator<Item = str>, \n / \r\n removed
    fn split(ref self, delim: u8) -> Split<Self>;       // view; TryIterator<Item = List<u8>>, delim removed

    // owning forms (2.23.1)
    fn into_lines(self) -> Owned<Lines<Self>, Self>;
    fn into_split(self, delim: u8) -> Owned<Split<Self>, Self>;
}

fn read_line() throws (IoError) -> str | none;          // stdin's next line without \n / \r\n; none at the end

Line and delimiter reads live only on BufRead, so they never cost a system call per byte. read_line appends to a StrBuf and returns the byte count, 0 at the end; a line that is not UTF-8 is InvalidData. io::read_line() is the convenient form for standard input. On an unbuffered stream, wrap it and close the wrapper: using r = io::BufReader::new(f) { try for l in r.lines() { .. } }, or own it with io::BufReader::new(f).into_lines().

BufRead is implemented by BufReader<R>, Cursor<T>, Stdin and Empty. The view fill_buf returns is valid until the next call on the stream. consume past the buffered bytes is a bug in the caller and panics with the type's name (BufReader::consume: 9 bytes past the 4 buffered; consume at most what fill_buf returned, likewise Cursor::consume and Stdin::consume).

#2.23.3. Write and Close

nabi
trait Write {
    fn write<B: AsBytes>(ref self, buf: B) throws (IoError) -> usize;   // some prefix of buf; its length
    fn flush(ref self) throws (IoError);

    // low level
    fn write_vectored(ref self, bufs: Slice<Slice<u8>>) throws (IoError) -> usize;  // default: the first non-empty buffer

    // convenient
    fn write_all<B: AsBytes>(ref self, buf: B) throws (IoError);        // all of buf; WriteZero if a write takes nothing
    fn write_display<T: Display>(ref self, x: T) throws (IoError);      // x through Display, no whole str built
    fn write_fmt(ref self, args: fmt::Arguments) throws (IoError);      // an f-string, piece by piece
}

#[lang("close_trait")]
trait Close {
    fn close(self) throws (IoError);
}

write and write_all take anything AsBytes (2.11): a str, a List<u8>, a Slice<u8>, a [u8; N]. Formatted output is an f-string: try w.write_all(f"{x}\n").

write_display writes one value as print shows it, in chunks as the value produces them (Formatter::from_sink, 2.10.2), so a large value is never built as one str. A failed write stops the formatting and is thrown as is, the chunks before it kept. A Display that fails by itself becomes an IoError of kind Other.

write_fmt writes an f-string the same way, its holes through Display and with no str of the whole text: try w.write_fmt(f"{name}: {value}\n") (2.10.15). Several values go in one f-string.

Close is the resource whose close can fail (2.13.4): its owner closes it with try x.close() or using, and leaving its scope open is an error. File, the sockets, the TLS connections, the child pipes, BufReader<R: Close>, BufWriter<W: Write + Close>, LineWriter<W: Write + Close>, Owned<V, R: Close> and Chain<A: Close, B: Close> implement it; the buffered writers write out the rest first. Its async twin is AsyncClose (2.23.5); try await x.close_async() closes the value as close does.

The halves of a split connection, net::ReadHalf<T> and net::WriteHalf<T> (3.2.1), implement Close and AsyncClose, ReadHalf the read traits (Read, AsyncRead) and WriteHalf the write traits (Write, AsyncWrite); the socket closes with the second half.

#2.23.4. Seek

nabi
enum SeekFrom { Start(u64), End(i64), Current(i64) }

trait Seek {
    fn seek(ref self, pos: SeekFrom) throws (IoError) -> u64;   // the new offset from the start
    fn rewind(ref self) throws (IoError);                       // seek(Start(0))
    fn stream_position(ref self) throws (IoError) -> u64;       // seek(Current(0))
}

Seek is implemented by File and Cursor<T>.

#2.23.5. Async traits

The async twins are separate traits: a Read that is not awaitable stays out of AsyncRead bounds, and an await never hides a blocking call. Their methods keep the _async suffix, so both kinds of method are in scope at once without ambiguity: f.read(buf) and await f.read_async(buf). consume never waits and has no _async form; on a type that implements both BufRead and AsyncBufRead call it as BufRead::consume(ref r, n).

AsyncRead / AsyncWrite are implemented by File (the call runs on a blocking thread, 3.1.4a), Socket, TcpStream, UnixStream, tls::Client / tls::Server, the child pipes, BufReader<R>, BufWriter<W>, LineWriter<W>, Cursor<T>, Empty, Sink and Repeat. An OS stream has one owner (2.13.4): let g = f moves it, and a second handle on the same stream is an explicit try_clone(). copy_async(r, w) borrows both when awaited where it is called: the caller still owns and closes them.

The async methods take ref self, as their sync twins do (refs-lang 4.12.13): the future holds the receiver, writes it back when it completes, and is awaited where it is made. close_async takes self: like close, it consumes the value.

AsyncClose is implemented by every Close type above that is also an async stream: File (the close runs on a blocking thread), Socket, TcpStream, TcpListener, UdpSocket, the Unix sockets, tls::Client / tls::Server (close_notify is sent without blocking), the child pipes, BufReader<R: AsyncClose>, BufWriter<W: AsyncWrite + AsyncClose>, LineWriter<W: AsyncWrite + AsyncClose>, Owned<V, R: AsyncClose> and Chain<A: AsyncClose, B: AsyncClose>. A socket's close does not wait, unless SO_LINGER makes it wait for unsent data; then it runs on a blocking thread.

Cancel safety: a socket's read_async / write_async cancelled while suspended moved no bytes; a File call that is cancelled still runs on its thread, and its result is lost. That thread works on its own copy of the bytes: after a cancel the caller's buffer is the caller's alone, and a read never writes into it later.

Only operations that are not stream I/O stay inherent _async methods of their types: opening and connecting (open_async, connect_async), accept_async, shutdown_async, datagrams (send_async, recv_from_async, ..), fd passing (send_with_fd_async), TLS control (close_notify_async, key_update_async) and processes (wait_async, output_async, status_async). The rule is 0.5.13.

#2.23.6. Buffers and Cursor

A buffer owns its inner stream: over an affine stream (a File, a socket) it is affine itself, with one owner. Cursor<T> and a buffer over a stream that is not affine are plain values: copies share the buffer and the position. BufWriter over a Close writer is closed by its owner: close() writes out the rest and closes the inner writer, so a buffered write error is never lost. A Cursor<List<u8>> overwrites from the position and then extends the list.

BufWriter<W: Write> and LineWriter<W: Write> also implement Drop: releasing one whose writer is not Close writes out the rest and drops a write error. To see that error, call flush() or into_inner() before the release.

nabi
using r = io::BufReader::new(try fs::open("data.txt")) {
    try for line in r.lines() {
        println(line);
    }
}

#2.23.7. copy and utilities

nabi
#[discardable]
fn copy<R: Read, W: Write>(ref r: R, ref w: W) throws (IoError) -> u64;

fn empty() -> Empty;            // Read + BufRead: always at the end
fn sink() -> Sink;              // Write: discards every byte
fn repeat(byte: u8) -> Repeat;  // Read: an endless stream of byte

struct Take<R> { .. }           // r.take(n), a view; limit(), set_limit(n)
struct Chain<A, B> { .. }       // a.chain(b); into_inner() -> (A, B); Close (A, B: Close), AsyncClose (A, B: AsyncClose)
struct Owned<V, R> { .. }       // r.into_lines() and the other owning forms; into_inner() -> R;
                                // TryIterator / Read / TryStream as V; Close (R: Close), AsyncClose (R: AsyncClose); Send (R: Send)

Every type in this chapter implements Debug; the streams, adapters and buffers (Take, Chain, Cursor, Empty, Sink, Repeat, BytesStream, LinesStream, Split, ..) print their type name.

copy reads r to its end into w and returns the byte count. Between two OS handles (files, sockets without timeouts or non-blocking mode, pipes) the runtime lets the kernel move the bytes (copy_file_range / sendfile / splice); other streams copy through read / write_all with an 8 KiB buffer.

#2.23.8. Standard streams

nabi
fn stdin() -> Stdin;            // Read + BufRead
fn stdout() -> Stdout;          // Write
fn stderr() -> Stderr;          // Write
fn read_line() throws (IoError) -> str | none;

stdout() shares the runtime buffer of print / println, so mixed output keeps its order; the buffer is flushed at a newline on a terminal, when full, at flush() and at exit. stderr is unbuffered. stdin() reads through the runtime's shared buffer; a Stdin handle buffers at most the rest of one line for fill_buf, so lines it has not consumed stay with that handle.

#input

io::input(prompt: str = "") throws (IoError) -> str | none writes prompt to stdout, flushes, and returns io::read_line(): the next line without its terminator, none at the end of input (Python's input(prompt), which raises there).

#2.23.9. Examples

Found a mistake? Edit this page on GitHub. Last updated