docs

你正在阅读 v0.1.2 的文档。Nabi 0.1.2 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#File and Network IO

本页内容

This chapter covers how a program talks to the world outside it. Files and directories, paths, standard IO, environment variables, child processes, and TCP / UDP sockets all live in std.

IO can fail at any time, so almost every function is throws (IoError). The try / catch from chapter 10 is used throughout. The examples write fn main() throws (IoError) to say what may fail; a plain fn main() may use try too, and an error that leaves it is printed and ends the program with exit code 1.

#Reading and writing files

The simplest way is fs::write and fs::read_to_str. The functions open and close the file for you. The example creates a directory under env::temp_dir(), works in it, and removes it at the end.

An IoError carries a kind() (NotFound, PermissionDenied, TimedOut, ResourceBusy when another process holds the file or device, ...) and a human-readable message. To branch on the kind of error, compare kind().

Path arguments accept either a str or a Path (the AsPath trait), so you can pass "a.txt" and dir / "a.txt" alike.

fs::lines(path) reads a file line by line, opening it at the first line and closing it after the last: try for line in fs::lines(p) { .. }. fs::glob(pattern) lists the paths that match, sorted: * and ? within a name, [a-z] for a set, and a ** component for any number of directories.

nabi
use std::{env, fs, process};

fn main() {
    let dir = env::temp_dir() / f"nabi_learn13_glob_{process::id()}";
    try fs::create_dir_all(dir / "src");
    try fs::write(dir / "a.txt", "one\ntwo\n");
    try fs::write(dir / "src" / "b.txt", "three\n");
    try for line in fs::lines(dir / "a.txt") { println(line); }
    for p in try fs::glob(f"{dir}/**/*.txt") {
        println(p.strip_prefix(dir) ?? p);
    }
    try fs::remove_dir_all(dir);
}
one
two
a.txt
src/b.txt

#File and its open functions

To write incrementally or read line by line, open a File directly. With a using block, the file is closed when the block exits; the statement using f = ..; closes it at the end of the enclosing block, as in show below. Closing a file can fail, so the compiler does not close one for you: bind it with using or call try f.close(); a File left open is a compile error. Each way of opening is its own function, so a wrong combination cannot be written: File::open (an existing file, read-only unless you pass an Access such as WriteOnly), File::create (created or emptied), File::create_new (fails when the file exists), File::open_or_create, and File::append (created when missing, every write at the end).

File::create creates or truncates a file, and File::open opens it read-only. Reads and writes are methods of the io::Read and io::Write traits, which every file has without a use. Line reading needs a buffer, so wrap the file in an io::BufReader; closing the reader closes the file. To keep the name, redeclare it: let f = BufReader::new(f); moves the file into the reader, so only the reader needs closing. lines() gives each line without its newline, and a read error ends the loop by throwing, so it is a try for.

r.lines() is a view of r: it reads through the reader and stays inside the scope of whoever owns r. Returning it from a function, keeping it past that scope, or capturing it in a task is a compile error (E0139) that names the fix:

error[E0139]: this returns a view of `r` out of `r`'s scope
  --> main.nabi:6:9
   |
 6 |         return r.lines();
   |         ^^^^^^
   |                --------- a view of `r` made here
   |
   = help: `r.lines()` reads through `r` and stays in its scope; use it there (`try r.lines().collect()`), or take the owning form `r.into_lines()`, which owns `r` and closes it with itself

Moving r ends its views the same way: after let kept = r;, a call that takes r by value, [move r], or storing r in a struct, a view made from it earlier can't be used. Finish with the view first, or move the owning form instead.

A reader or file made only for one call that borrows it, as in (try File::open(p)).read_to_str() or BufReader::new(try File::open(p)).lines(), has no owner after the call, so nothing would close it. That is E0134; bind it first: using f = try File::open(p);, then try f.read_to_str().

When the lines must leave the scope, use the owning form r.into_lines(). It returns an io::Owned, which takes the reader, closes it when you close the lines (try ls.close()), gives it back with into_inner(), and can be returned or moved into a task (it is Send when the reader is):

The same pairs exist for bytes / into_bytes, split / into_split, take / into_take, the async lines_async / into_lines_async and bytes_async / into_bytes_async, and a listener's incoming / into_incoming. a.chain(b) always owns both readers and closes both, and into_inner() gives back the pair. A take view has no into_inner(); to get the reader back afterwards, use into_take and its into_inner().

#Directories and the Dir capability

fs::walk traverses a directory depth-first, in name order. fs::read_dir lists only one level. Reading a directory can fail at any entry, so both are stepped with try for.

Dir is a little special: a Dir handle is a capability. Dir::root() is the default handle that works with ordinary paths, and a Dir opened from it with open_dir can only reach inside that directory. Attempts to escape with an absolute path or .. are refused. This is a safety net when handling untrusted paths (user input, names inside an archive).

create_dir, remove_file, remove_dir, rename, copy, and metadata are also available both as free functions and as Dir methods.

#Paths: Path

std::path::Path is a UTF-8 path. Like Python's pathlib, you join paths with the / operator. A path may have no parent or extension, so those methods return T | none.

nabi
use std::path::Path;

let p = Path::new("/home/nabi/src/main.nabi");
println(f"parent:    {p.parent() ?? Path::empty()}");
println(f"file name: {p.file_name() ?? "-"}");
println(f"stem:      {p.file_stem() ?? "-"}");
println(f"extension: {p.extension() ?? "-"}");
println(f"absolute:  {p.is_absolute()}");

let q = Path::new("docs") / "guide" / "intro.md";
println(f"joined:    {q}");
println(f"swapped:   {q.with_extension("html")}");
println(f"normal:    {Path::new("a/./b/../c").normalize()}");
for c in q.components() { print(f"[{c.as_str()}]"); }
println("");
parent:    /home/nabi/src
file name: main.nabi
stem:      main
extension: nabi
absolute:  true
joined:    docs/guide/intro.md
swapped:   docs/guide/intro.html
normal:    a/c
[docs][guide][intro.md]

normalize only cleans up the string; canonicalize asks the file system and resolves symbolic links too.

#Standard IO and the environment

print writes without a newline and eprint / eprintln write to standard error; for buffered or explicit writes, use io::stdout() / io::stderr(). io::input("Your name? ") writes the prompt, flushes it and returns the next line without its newline, or none at end of input, as Python's input does; io::read_line() does the same without a prompt; to read every line, write try for line in io::stdin().lines(). The io module and the Read / Write traits need no use.

nabi
use core::io::IoError;

fn main() throws (IoError) {
    let out = io::stdout();
    try out.write_all("Your name? ");
    try out.flush();
    match try io::read_line() {
        line: str => println(f"Hello, {line.trim()}!"),
        none => println("(no input)"),
    }
    try io::stderr().write_all("bye\n");
}

Command-line arguments and environment variables live in std::env. Element 0 of env::args() is the executable path. env::var throws VarError if the variable is not set.

nabi
use std::env;

let args = env::args();
println(f"{args.len()} arg(s)");

unsafe { try! env::set_var("NABI_GREETING", "annyeong"); }
println(try env::var("NABI_GREETING") catch _ { "unset" });
unsafe { try! env::remove_var("NABI_GREETING"); }
println(try env::var("NABI_GREETING") catch e { f"error: {e}" });

let mine = env::vars().filter(|kv| kv.0.starts_with("NABI_GREETING")).count();
println(f"matching vars: {mine}");
println(f"temp is absolute: {env::temp_dir().is_absolute()}");
1 arg(s)
annyeong
error: environment variable not found
matching vars: 0
temp is absolute: true

set_var and remove_var are unsafe and throw. Nabi's own env functions share a lock, but nothing stops C code from reading the environment at the same moment, so change it before you spawn threads. A name that is empty or holds = or a NUL throws IoError (InvalidInput). To set a variable for one child process only, use Command::env, which needs no unsafe.

#Child processes

process::Command runs another program. Set arguments, environment, and working directory with builder methods, then run it with one of output() (waits for exit and collects stdout / stderr), status() (exit status only), or spawn() (returns a Child without waiting).

nabi
use std::process::Command;
use core::io::IoError;

fn main() throws (IoError) {
    let out = try Command::new("echo").args(["hello", "from", "echo"]).output();
    print(try str::from_utf8(out.stdout) catch _ { "" });
    println(f"success: {out.status.success()}");

    let st = try Command::new("sh").args(["-c", "exit 3"]).status();
    println(f"code: {st.code() ?? -1}");

    try Command::new("no-such-program").status() catch e {
        println(f"spawn failed: {e.kind():?}");
    };
}
hello from echo
success: true
code: 3
spawn failed: NotFound

out.stdout is bytes (List<u8>), so convert it to text with str::from_utf8. When you only want the output as text, process::run("git", ["status"]) runs the program to completion and returns its stdout; a nonzero exit throws an ExitStatusError whose status() and stderr() say what happened. For a process killed by a signal, code() is none; on Linux and macOS st.signal() names the signal (Signal::Kill, ..). A builder method returns a changed copy and leaves the command it was called on as it was, so let base = Command::new("git"); let log = base.arg("log"); keeps base without log.

A child's streams go where Stdio says. With Stdio::Piped, take each pipe from the Child with take_stdin(), take_stdout() or take_stderr() (none if that stream is not piped or was already taken); the taker owns it and closes it. A File moved into Stdio::File(f) belongs to the command: running it closes your copy, so f is gone after the move, and the child keeps its own. One command with a Stdio::File runs once; to run it again, give it a new file (f.try_clone()). A Stdio::File value has one owner too: giving it to two commands, or to two streams of one command (.stdout(s).stderr(s)), is an error (E0133); give each its own Stdio::File(try f.try_clone()). Stdio::Inherit, Null and Piped hold nothing and can be reused. A Stdio::File that is never given to a command must be closed (try s.close()), like its File.

The Child has one owner, the one that waits on it. To stop the child from somewhere else while that owner waits (a timeout, a shutdown), take child.handle(): a ChildHandle that another thread or task uses to kill() or send_signal(..) the child. It owns no pipe and no wait, h.id() gives the child's process id, and once the child has ended a signal through it does nothing.

#TCP and UDP

The std::net API is blocking by default. The example below runs a server and a client in one program. Binding to port 0 lets the OS pick a free port, and local_addr() reports the actual address. The server accepts one connection on a thread and echoes the received text back in upper case.

An address can be a SocketAddr, "host:port" text (names are looked up), an (IpAddr, u16) pair or a list of addresses: TcpStream::connect, TcpListener::bind and UdpSocket::bind take anything that implements ToSocketAddrs and try the addresses in order. net::tcp_connect, net::tcp_listen and net::udp_bind are the same calls as free functions.

A socket's close can fail, so every socket is closed by its owner, try s.close() or using; the compiler refuses a program that leaves one open.

To read and write one connection at once, from two threads or tasks, split() it into a ReadHalf and a WriteHalf. Each half owns its direction and is closed by its owner. Closing the write half ends the stream for the peer, as shutdown(Shutdown::Write) does, while the read half reads the reply; the socket closes with the second half. shutdown(Shutdown::Both) on either half shuts the socket down both ways and wakes a read blocked on the other half. r.unsplit(w) gives the connection back. UnixStream and the TLS connections split the same way.

UDP exchanges datagrams without a connection. recv_from returns the number of bytes received and the sender's address.

nabi
use std::net;
use core::io::IoError;

fn main() throws (IoError) {
    let a = try net::udp_bind("127.0.0.1:0");
    let b = try net::udp_bind("127.0.0.1:0");
    try b.send_to("ping", try a.local_addr());

    let buf = List::filled(64, 0u8);
    let (n, from) = try a.recv_from(buf);
    println(f"got {n} bytes: {try str::from_utf8(buf[0:n]) catch _ { "?" }}");
    println(f"from b: {from == (try b.local_addr())}");
    try a.close();
    try b.close();
}
got 4 bytes: ping
from b: true

Below these sits net::Socket, the socket as the OS has it: you pick the domain, type and protocol, set options such as set_reuse_address or set_only_v6, and call bind / listen / connect yourself. TcpListener::from(s) (or TcpStream::from, UdpSocket::from) then takes it over.

nabi
use std::net::{Socket, Domain, SocketType, Protocol, TcpListener};
use core::io::IoError;

fn main() throws (IoError) {
    let s = try Socket::new(Domain::Ipv4, SocketType::Stream, Protocol::TCP);
    try s.set_reuse_address(true);
    try s.bind(try! "127.0.0.1:0".parse());
    try s.listen(16);
    let l = TcpListener::from(s);
    println(f"listening on port 0: {(try l.local_addr()).port() > 0}");
    try l.close();
}
listening on port 0: true

#Async IO: *_async

Inside a task (see chapter 12), instead of a blocking call you await the version of the same name with an _async suffix. For sockets, only the task pauses while waiting, and the thread runs other tasks. Regular files have no OS support for async waiting, so the call runs on a separate thread while the task awaits the result. Errors are thrown exactly as in the synchronous version.

The stream calls come from the io traits. AsyncRead, AsyncWrite, AsyncSeek and AsyncClose give read_async, write_all_async, flush_async, seek_async and close_async to every file, socket, TLS connection and child pipe, and to your own code bounded by them. close_async closes the value as close does, so it counts as closing it. Only what is not reading or writing a stream is a method of its type: connect_async, accept_async, shutdown_async, and for child processes Child::wait_async, Command::output_async and Command::status_async. An async method updates the value it is called on, so await it where you call it (chapter 12).

With thousands of connections, tasks are much lighter than a thread per connection. For a tool with only a few connections, the blocking API is simpler.

#Summary

  • Whole files: fs::read_to_str / fs::write. Incrementally: File + using, opened with the function for the way you need (open, create, create_new, open_or_create, append).
  • Dir is a capability. Anything outside an opened Dir (absolute paths, ..) is refused with PermissionDenied.
  • Build paths with Path and the / operator; parts that may be missing come back as T | none.
  • Use io::stdin/stdout/stderr, env::args/var/temp_dir, io::input, and process::run / process::Command to deal with the outside environment. fs::lines and fs::glob read lines and match paths.
  • TCP / UDP: TcpListener::bind / TcpStream::connect / UdpSocket::bind (or net::tcp_listen / net::tcp_connect / net::udp_bind) over ToSocketAddrs; net::Socket for every option. With port 0, the OS picks one. Close each socket: try s.close() or using. split() a connection to read and write it from two threads or tasks.
  • Inside a task, await the *_async versions; close with try await s.close_async().
  • r.lines() and the other adapters are views that stay in r's scope; r.into_lines() and the other into_ forms own the reader and can leave it.

#Further reading

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