std.fs - ZZ
Comprehensive non-blocking filesystem. All fallible ops return Result<_, str> with unified fs:<op>:<code>: <path> diagnostics (identical on VM/AOT). Predicates return bool. Open handles are Opaque("file") and dispatch file.* methods. Pluggable providers: Os / Mem / Tar / Embed.
import std.fsPurpose
Section titled “Purpose”std.bytes holds arbitrary binary data safely — no UTF-8 validation, no lossy decoding. Produced by std.fs.read_bytes, fs.read_chunk_bytes, fs.read_bytes_at, and bytes.finish. Use for file uploads, ciphertext, binary protocols, and any payload that isn’t valid UTF-8.
bytes is immutable (b[i] = x is an error). Slices (b[1:4]) share the underlying store with zero copies.
Quickstart
Section titled “Quickstart”import std.bytesimport std.fs
match fs.read_bytes("data.bin") { .ok(b) => { println(len(b)) // or b.len() println(b[0]) // u8 as int (negatives wrap) println(b[1:4]) // zero-copy slice -> bytes println(typeof(b)) // bytes for x in b { println(x) } // iterate ints } .err(e) => println(e),}
// Build binary incrementallybuf := bytes.builder()buf = bytes.push_byte(buf, 0x48) // 'H'buf = bytes.push_byte(buf, 0x65) // 'e'match bytes.finish(buf) { .ok(b) => println(b), // "He" .err(e) => println(e),}Performance notes
Section titled “Performance notes”- Slices are zero-copy (share the store).
bytes.builder+push_byte+finishis O(n); never concatenate binary in a loop.read_bytescaches content in the process-wide FS cache (seestd.fs).- Immutable — safe to share across tasks without locking.
Production patterns
Section titled “Production patterns”import std.bytesimport std.cryptoimport std.encoding
// Hash a binary filematch fs.read_bytes("payload.bin") { .ok(b) => { println(crypto.sha256_bytes(b)) // hex digest over raw bytes } .err(e) => println(e),}
// Base64 round-trip preserving binarymatch encoding.base64_decode_bytes("aGk=") { .ok(raw) => println(bytes.to_ints(raw)[0]), // first byte as int .err(e) => println(e),}Purpose
Section titled “Purpose”std.fs covers file read/write, directory ops, streaming handles, path lexing, and pluggable FS providers (Os / Mem / Tar / Embed). Reads share a process-wide stat-validated content cache. All paths use / separators internally (backslash accepted, ./.. resolved).
Quickstart
Section titled “Quickstart”import std.fs
match fs.read("data.txt") { .ok(content) => println(content), .err(e) => println("Error: {e}"),}match fs.write("out.txt", "Hello World") { .ok(_) => println("Written"), .err(e) => println("Error: {e}"),}if fs.exists("config.toml") { println("config found")}Bytes — contiguous buffers
Section titled “Bytes — contiguous buffers”read_bytes, read_chunk_bytes, read_bytes_at return bytes: one contiguous buffer (~1 byte RSS per byte), slices share zero-copy, prints like [104, 105], immutable (b[i] = x errors), JSON as int arrays.
match fs.read_bytes("data.bin") { .ok(b) => { println(len(b)) // or b.len() println(b[0]) // u8 as int println(b[1:4]) // zero-copy slice -> bytes for x in b { println(x) } } .err(e) => println(e),}read_chunk is text (lossy on arbitrary bytes); use read_chunk_bytes for binary.
Streaming handles
Section titled “Streaming handles”import std.fs
func main() -> Result<int, str> { match fs.open("log.txt", "a") { .ok(f) => { fs.write_chunk(f, "line\n")? fs.flush(f)? fs.close(f)? } .err(e) => println(e), } return .ok(0)}fs.read_chunk(f, n) (text, "" at EOF), fs.read_chunk_bytes(f, n) (bytes, empty at EOF), fs.write_chunk(f, data), fs.seek(f, pos), fs.flush(f), fs.close(f).
Path helpers (pure lexical, no I/O)
Section titled “Path helpers (pure lexical, no I/O)”| Function | Description |
|---|---|
fs.normalize(path) |
Lexical normalize (./.., roots, separators) |
fs.join(a, b) |
Join + normalize (b wins when absolute) |
fs.basename(path) |
Final segment |
fs.dirname(path) |
Directory part |
fs.is_absolute(path) |
Rooted check (/x, C:\x, \\unc\…) |
fs.extension(path) |
Extension without dot |
FS providers (fs.FS handle interface)
Section titled “FS providers (fs.FS handle interface)”match fs.memfs() { .ok(m) => { fs.write_at(m, "a/b.txt", "hello") match fs.read_to_string_at(m, "a/b.txt") { .ok(c) => println(c), .err(e) => println(e), } } .err(e) => println(e),}fs.osfs()— real OS filesystem.fs.memfs()— thread-safe in-memory tree (tests, caches).fs.tarfs(path)— read-only plain.tarview (regular files + dirs; symlinks/devices skipped).fs.embedfs()— read-only--embedassets (empty unless CLI got--embed <dir>).
*_at ops: read_to_string_at, read_bytes_at, write_at, append_at, exists_at, is_file_at, is_dir_at, read_dir_at, mkdir_all_at, remove_file_at.
Power helpers
Section titled “Power helpers”fs.scan_counts(path, markers, bstart, bend, nested, whole)— fused read + NUL-sniff +str.classify→[lines, code, comments, blanks, binary].fs.is_generated(path, markers)— minified/generated-content heuristic.
Embed at build time
Section titled “Embed at build time”zz build --embed ./assets main.zzzz run --embed ./assets main.zzMethod syntax
Section titled “Method syntax”File handles dispatch method calls:
import std.fs
func main() -> Result<int, str> { f := fs.open("log.txt", "a")? f.write_chunk("line\n")? f.flush()? f.close()? return .ok(0)}Gotchas
Section titled “Gotchas”- All fallible ops return
fs:<op>:<code>: <path>diagnostics — identical on VM/AOT. - Reads are cached (stat-validated); writes/removals invalidate eagerly; outside writes detected by len/mtime.
read_chunkis lossy on arbitrary bytes — useread_chunk_bytesfor binary.bytesare immutable —b[i] = xis an error.fs.renamewas removed — usefs.move.
Production patterns
Section titled “Production patterns”import std.fs
// Atomic-ish write: write to temp, then movefunc write_atomic(path: str, content: str) -> Result<unit, str> { tmp := "{path}.tmp" return match fs.write(tmp, content) { .ok(_) => fs.move(tmp, path), .err(e) => .err(e), }}
func main() -> Result<int, str> { // In-memory test fs match fs.memfs() { .ok(mem) => { fs.write_at(mem, "config.toml", "key = 'val'")? println(fs.read_to_string_at(mem, "config.toml")?) } .err(e) => println(e), } return .ok(0)}Purpose
Section titled “Purpose”std.path resolves, joins, and inspects paths without touching the disk. Separator style follows std.env.os() ("windows" → \, else /). Use for building paths before passing them to std.fs.
API reference
Section titled “API reference”52 entries. Signatures come from the compiler’s own FuncSig table, so they match the runtime exactly; descriptions come from the module guide.
Full index: API reference · Standard library