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 超過已緩衝的位元組是呼叫者的錯誤,會以型別名稱觸發 panic(BufReader::consume: 9 bytes past the 4 buffered; consume at most what fill_buf returned,Cursor::consume 與 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 與 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:無法 await 的 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) 在其被呼叫處 await 時借用兩者:呼叫者仍擁有並關閉它們。

非同步方法與其同步對應版本一樣接受 ref self(refs-lang 4.12.13):future 持有接收者,完成時將其寫回,並在建立之處被 await。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 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)

本章的每個型別都實作 Debug;串流、配接器與緩衝區(Take、Chain、Cursor、Empty、Sink、Repeat、BytesStream、LinesStream、Split、..)印出其型別名稱。

copy 將 r 讀到結尾並寫入 w,回傳位元組數。在兩個作業系統控制代碼之間(檔案、未設逾時也未設非阻塞模式的通訊端、管道),執行環境讓核心搬移位元組(copy_file_range / sendfile / splice);其他串流則以 8 KiB 的緩衝區透過 read / write_all 複製。

#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 上編輯此頁 最後更新: