docs

#2.23. io:::字节流与标准 I/O

本页内容

core::io 包含 Nabi 的全部 I/O 词汇:错误类型,流 trait Read、BufRead、Write 和 Seek 及其异步孪生版本 AsyncRead、AsyncBufRead、AsyncWrite 和 AsyncSeek,Close 和 AsyncClose,缓冲区、Cursor、copy 以及标准流。与操作系统打交道的类型(File、套接字、TLS 连接、子进程管道)位于 std 中并实现这些 trait;这里的一切都与目标无关,标准流在每个目标上都存在(在浏览器中,stdout / stderr 输出到宿主控制台,stdin 处于末尾,0.1.4)。

prelude 提供了模块名 io 以及 trait Read、Write、AsyncRead 和 AsyncWrite,所以 io::stdin()、io::BufReader::new(f) 和 f.read(buf) 都不需要 use。BufRead、Seek、AsyncBufRead 和 AsyncSeek 在约束中写作 io::BufRead 等;它们的方法无需导入即可解析。没有 std::io。

每个流方法只有一个定义:File、TcpStream、UnixStream、tls::Client 和 tls::Server 没有固有的 read / write / read_to_end / flush 方法,也没有它们的 _async 孪生版本;这些调用通过 trait 解析。

#2.23.0. IoError

kind() 来自操作系统错误码(UnexpectedEof、InvalidData 和 WriteZero 由库设置);错误码本身是 os_code(),操作系统的描述(运行时的 strerror)是 message()。对于库自己产生的错误(IoError::new(InvalidInput, ".."))以及无法解析的名称(3.2.4),os_code() 为 none:解析器(EAI)的错误码不是操作系统错误码。这样的查找失败保留解析器的消息,名称不存在时为 NotFound,否则为 Other。在 Windows 上,查找失败时得到 Winsock 错误码,由 os_code() 返回。IoErrorKind 是 #[non_exhaustive]:在 core 之外 match 需要 _ 分支。

last_os_error() 是对本线程上最后一次 #[errno] C 调用所保存的错误码调用 from_os_code 的结果(stdlib 1.7.11):在 Windows 上,其 GetLastError 非零时取它,否则取其 errno;在其他平台上取其 errno。没有用 #[errno] 声明的调用不保存任何内容,因此错误码来自更早的调用。

#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 是唯一必需的方法。缓冲区是 SliceMut<u8>(2.9):List<u8> 作为整个列表的视图传入,buf[a:b] 读入其中一部分。read_to_end_into 读入列表的空闲容量,不先填零:它是 read_to_end 精确的低层形式。

bytes 和 take(以及 lines、split、bytes_async、lines_async 和 TcpListener::incoming)返回流的作用域视图:适配器通过流读取,流保持其唯一的所有者(2.13.4),仍由该所有者关闭它。视图与锁守卫的值一样,停留在流所有者的作用域内(2.16.3):返回它、把它存放到该作用域之外、把它传给会保留它的被调用方,或在流已关闭或已移动后使用它,都是编译错误 E0139。只读取流的调用会借出流(r.capacity()、f"{r:?}"、被调用方不保留的按值参数,同 2.13.4),流的视图继续有效。视图既不是 Send 也不是 Sync,所以任务不能捕获视图。以 ref r 接受流的辅助函数可以返回它的视图:这时视图与调用方的流绑定。

into_ 形式是拥有所有权的适配器:r.into_lines() 接管 r 并返回 Owned<V, R>,它像视图 V 一样迭代(读取、作为流),与自身一起关闭 r(Close / AsyncClose),并可用 into_inner() 交还 r。在所有者的作用域内使用视图(using r = .. { try for l in r.lines() { .. } });当适配器必须离开作用域时使用拥有所有权的形式:从函数返回、保存在结构体中,或移动到任务中。chain 总是拥有两个流:它会关闭两者,into_inner() 返回这一对流。bytes 每个字节调用一次 read;对无缓冲的流,先用 BufReader 包装。

#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

按行和按分隔符的读取只存在于 BufRead 上,因此绝不会每个字节一次系统调用。read_line 追加到 StrBuf 并返回字节数,末尾时返回 0;不是 UTF-8 的行是 InvalidData。io::read_line() 是针对标准输入的便捷形式。对无缓冲的流,包装它并关闭包装器:using r = io::BufReader::new(f) { try for l in r.lines() { .. } },或者用 io::BufReader::new(f).into_lines() 拥有它。

BufRead 由 BufReader<R>、Cursor<T>、Stdin 和 Empty 实现。fill_buf 返回的视图在下一次对该流调用之前有效。consume 超出已缓冲的字节属于调用方的 bug,会触发 panic 并给出类型名(BufReader::consume: 9 bytes past the 4 buffered; consume at most what fill_buf returned,Cursor::consume 和 Stdin::consume 同理)。

#2.23.3. Write 与 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 和 write_all 接受任何 AsBytes(2.11):str、List<u8>、Slice<u8>、[u8; N]。格式化输出用 f-string:try w.write_all(f"{x}\n")。

write_display 按 print 显示的样子写出一个值,按值产生的块逐块写出(Formatter::from_sink,2.10.2),所以大的值永远不会被构造成一个完整的 str。写入失败会停止格式化,并原样抛出该错误,之前的块保留。自身失败的 Display 变为种类为 Other 的 IoError。

write_fmt 以同样方式写出 f-string,其中的空位通过 Display 输出,不生成整段文本的 str:try w.write_fmt(f"{name}: {value}\n")(2.10.15)。多个值放在一个 f-string 中。

Close 是关闭可能失败的资源(2.13.4):它的所有者用 try x.close() 或 using 关闭它,不关闭就离开其作用域是错误。File、各种套接字、TLS 连接、子进程管道、BufReader<R: Close>、BufWriter<W: Write + Close>、LineWriter<W: Write + Close>、Owned<V, R: Close> 和 Chain<A: Close, B: Close> 实现了它;带缓冲的写入器会先写出剩余内容。它的异步孪生版本是 AsyncClose(2.23.5);try await x.close_async() 与 close 一样关闭该值。

拆分后连接的两半,即 net::ReadHalf<T> 和 net::WriteHalf<T>(3.2.1),实现 Close 和 AsyncClose,ReadHalf 实现读取 trait(Read、AsyncRead),WriteHalf 实现写入 trait(Write、AsyncWrite);套接字随第二个半边关闭。

#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 由 File 和 Cursor<T> 实现。

#2.23.5. 异步 trait

异步孪生版本是独立的 trait:不可等待的 Read 不满足 AsyncRead 约束,await 也永远不会隐藏阻塞调用。它们的方法保留 _async 后缀,所以两类方法可以同时在作用域内而不产生歧义:f.read(buf) 与 await f.read_async(buf)。consume 从不等待,没有 _async 形式;在同时实现了 BufRead 和 AsyncBufRead 的类型上,以 BufRead::consume(ref r, n) 的形式调用它。

AsyncRead / AsyncWrite 由 File(调用在阻塞线程上运行,3.1.4a)、Socket、TcpStream、UnixStream、tls::Client / tls::Server、子进程管道、BufReader<R>、BufWriter<W>、LineWriter<W>、Cursor<T>、Empty、Sink 和 Repeat 实现。操作系统流只有一个所有者(2.13.4):let g = f 会移动它,同一个流的第二个句柄需要显式调用 try_clone()。copy_async(r, w) 在调用处被等待时借用两者:仍由调用方拥有并关闭它们。

与同步孪生版本一样,异步方法接受 ref self(refs-lang 4.12.13):future 持有接收者,完成时把它写回,并在创建处被等待。close_async 接受 self:它与 close 一样消耗该值。

AsyncClose 由上面所有同时也是异步流的 Close 类型实现:File(关闭在阻塞线程上运行)、Socket、TcpStream、TcpListener、UdpSocket、Unix 套接字、tls::Client / tls::Server(close_notify 以非阻塞方式发送)、子进程管道、BufReader<R: AsyncClose>、BufWriter<W: AsyncWrite + AsyncClose>、LineWriter<W: AsyncWrite + AsyncClose>、Owned<V, R: AsyncClose> 和 Chain<A: AsyncClose, B: AsyncClose>。套接字的关闭不会等待,除非 SO_LINGER 让它等待未发送的数据;这时它在阻塞线程上运行。

取消安全性:套接字的 read_async / write_async 在挂起时被取消,不会移动任何字节;被取消的 File 调用仍在其线程上运行,其结果丢失。该线程操作的是字节的独立副本:取消之后,调用方的缓冲区只归调用方所有,之后的读取绝不会写入它。

只有不属于流 I/O 的操作保留为其类型的固有 _async 方法:打开和连接(open_async、connect_async)、accept_async、shutdown_async、数据报(send_async、recv_from_async 等)、fd 传递(send_with_fd_async)、TLS 控制(close_notify_async、key_update_async)以及进程(wait_async、output_async、status_async)。规则见 0.5.13。

#2.23.6. 缓冲区与 Cursor

缓冲区拥有其内部流:基于仿射流(File、套接字)的缓冲区本身也是仿射的,只有一个所有者。Cursor<T> 以及基于非仿射流的缓冲区是普通值:副本共享缓冲区和位置。基于 Close 写入器的 BufWriter 由其所有者关闭:close() 写出剩余内容并关闭内部写入器,因此带缓冲的写入错误永远不会丢失。Cursor<List<u8>> 从当前位置开始覆盖,然后扩展列表。

BufWriter<W: Write> 和 LineWriter<W: Write> 也实现了 Drop:释放一个其写入器不是 Close 的缓冲写入器时,会写出剩余内容并丢弃写入错误。要看到该错误,在释放之前调用 flush() 或 into_inner()。

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

#2.23.7. copy 与工具

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)

本章的每个类型都实现了 Debug;流、适配器和缓冲区(Take、Chain、Cursor、Empty、Sink、Repeat、BytesStream、LinesStream、Split 等)打印其类型名。

copy 把 r 读到末尾并写入 w,返回字节数。在两个操作系统句柄(文件、没有超时也不是非阻塞模式的套接字、管道)之间,运行时让内核移动字节(copy_file_range / sendfile / splice);其他流通过 read / write_all 用 8 KiB 缓冲区复制。

#2.23.8. 标准流

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

stdout() 与 print / println 共享运行时缓冲区,所以混合输出保持顺序;缓冲区在终端上遇到换行时、写满时、flush() 时以及退出时刷新。stderr 无缓冲。stdin() 通过运行时的共享缓冲区读取;Stdin 句柄为 fill_buf 最多缓冲一行的剩余部分,因此它尚未消耗的行留在该句柄中。

#input

io::input(prompt: str = "") throws (IoError) -> str | none 把 prompt 写到 stdout,刷新,然后返回 io::read_line():下一行(不含行终止符),输入结束时为 none(相当于 Python 的 input(prompt),后者在这种情况下抛出异常)。

#2.23.9. 示例

发现错误? 在 GitHub 上编辑此页 最后更新: