sysl

Module

sysl.fs

What is at the end of a path: reading and writing whole files, metadata, directories, links, and the errors any of it can answer with.

Import import sysl.fs
Requires
requires { os }

read_text, write_bytes, write_text_atomic and the other publishing calls, metadata, make_dir_all, copy_file, canonicalize, the walk, map_file for a file’s bytes mapped rather than read, and IoError — which carries the platform’s own number so that a caller can act on which failure it was rather than only on there having been one.

This module requires os and sysl.path requires nothing, which is why they are two. A capability requirement is module-wide, so one getcwd filed beside join would take path handling away from every program with no operating system to ask. Deciding what a path says is sysl.path‘s; going and looking is this module’s.

Index

unchanged append append_bytes append_text cache_dir canonicalize config_dir copy_dir_all copy_file create create_update current_dir data_dir entries entry_bytes executable exists from_errno get_xattr hard_link home_dir is_dir is_file is_link link_get_xattr link_list_xattrs link_metadata link_remove_xattr link_set_times link_set_xattr list_xattrs make_dir make_dir_all make_temp_dir map_file metadata open open_dir open_options open_uncached open_update open_with page_size pending_name publish_dir publish_file read_bytes read_link read_text readable remove_dir remove_dir_all remove_file remove_xattr rename rename_no_replace set_current_dir set_link_owner set_modified set_owner set_permissions set_times set_xattr size_of space symlink temp_dir temp_file temp_root truncate walk writable write_bytes write_bytes_atomic write_text write_text_atomic Advice Dir Entry File FileState IoError Kind LockKind Mapped MappedMut Matching Meta OpenOptions Space Walk Display for IoError Display for Kind Drop for Dir Drop for FileState Drop for Mapped Drop for MappedMut Eq for IoError Eq for Kind Fallible for File Iterate for Matching Iterate for Walk Positioned for File ReadAt for File Reader for File WriteAt for File Writer for File

Constants

unchanged

const unchanged: u32 = …

What set_owner and set_link_owner take for an owner or a group to leave as it is: 4294967295, which is (uid_t)-1 and (gid_t)-1, the value chown(2) itself reads as “no change”. No account has that id.

Functions

append

append(path: string, mode: u32 = file_mode) -> Result[File, IoError]

append_bytes

append_bytes(path: string, bytes: []const u8, mode: u32 = file_mode) -> Result[unit, IoError]

Writes the bytes at the end of the file, making it if it is not there. Each call lands after whatever the file already held, including anything another program appended in between.

mode is the permission bits of a file this call makes, as write_bytes takes them; a file that is already there keeps its own.

append_text

append_text(path: string, text: string, mode: u32 = file_mode) -> Result[unit, IoError]

append_bytes for text, with the same mode.

cache_dir

cache_dir() -> Option[string]

Where a program’s own cache belongs – the things it can regenerate and would rather not.

~/Library/Caches on macOS, %LOCALAPPDATA% on Windows, and $XDG_CACHE_HOME or ~/.cache elsewhere, which is the freedesktop rule.

A program appends its own name and nothing here does it for you: this answers where the machine keeps caches, not where yours goes, so the call is cache_dir().map((d) -> join(d, "myprogram")). A library that guessed the leaf would be guessing the program’s identity.

canonicalize

canonicalize(path: string) -> Result[string, IoError]

The path the filesystem agrees on: every ., every .. and every symbolic link resolved, and the answer absolute.

This is not sysl.path.normalize, and the difference is a security bug when it is not known. normalize is string surgery and touches no disk; where a/b is a link to /elsewhere, a/b/../c normalizes to a/c and canonicalizes to /c – two different files. Every path so far has to exist, which is the price of the real answer and is also a useful check in itself.

config_dir

config_dir() -> Option[string]

Where a program’s configuration belongs – what a person edits, and what survives a reinstall.

~/Library/Application Support on macOS, %APPDATA% on Windows, $XDG_CONFIG_HOME or ~/.config elsewhere.

macOS answers the same directory for this and for data_dir, and that is Apple’s convention rather than an omission here. The platform draws the line between cache and everything else and does not draw one between configuration and data; a library that invented a ~/Library/Config to make the four look symmetrical would be putting files where nothing else on the machine looks.

copy_dir_all

copy_dir_all(from: string, to: string) -> Result[unit, IoError]

A directory and everything under it copied, making the destination and everything under it.

A directory is merged into and a file is never overwritten. Those are the safe half of each question: a destination that already holds a subtree gains what this brings, and a destination that already holds a file of a name being copied reports AlreadyExists rather than quietly replacing something. make_dir_all is idempotent, so the merge half is simply what happens.

Permissions are carried, which is where this differs from copy_file – an executable copied with that one stops being executable, and this org copies build inputs. A symbolic link is copied as a link, pointing wherever it pointed, which may be nothing and may be outside the tree. A target whose chmod is unsupported has no permission bits to carry, and the copy goes on without them; any other error from setting them fails the copy.

A failure part way through leaves what it has already written. Nothing here removes a tree on the way out, because it cannot know whether the destination existed before it started, and deleting one the caller owned would be far worse than the failure being reported. A caller that needs the destination to appear whole or not at all copies to pending_name(to) and hands that to publish_dir – a copy built beside its destination rather than in make_temp_dir, since a rename only moves a directory within one filesystem, and that rename is the only atomicity a filesystem has.

The source may be a plain file, in which case this is copy_file with the mode carried.

copy_file

copy_file(from: string, to: string) -> Result[unit, IoError]

One file copied to another path, replacing whatever was at the destination.

It is a read-and-write loop rather than a platform fast path, which is a decision rather than an omission. copyfile(3) on macOS and copy_file_range(2) on Linux can hand the whole thing to the kernel, and on a filesystem that supports reflinks they can do it without moving any data at all – but the two have different names, different signatures and different failure modes, and neither is reachable without a shim per platform. What is here is correct everywhere and is what every caller needs; the fast path is worth adding the day something measures that it is missed.

The permission bits are not carried over. The destination is made the way create makes any file, which is what the process umask decides. A caller that wants the mode preserved reads metadata(from).permissions() and writes it with set_permissions, which says out loud that it is doing so – and a copy that silently reproduced a 0o600 into a directory where that was not intended is the kind of surprise a library should not spring.

create

create(path: string, mode: u32 = file_mode) -> Result[File, IoError]

create_update

create_update(path: string, mode: u32 = file_mode) -> Result[File, IoError]

current_dir

current_dir() -> Result[string, IoError]

Where the program is, which nothing in the library could ask before.

sysl.process takes a dir for a child to start in, so a program could say where somebody else should be and not where it was itself. This is the other half.

It is a global the whole process shares, so a threaded program that reads this while another thread is calling set_current_dir gets one of the two answers and no promise about which. Building an absolute path once at start-up is the shape that avoids the question.

data_dir

data_dir() -> Option[string]

Where a program’s own data belongs – what it wrote and cannot regenerate.

~/Library/Application Support on macOS, %APPDATA% on Windows, $XDG_DATA_HOME or ~/.local/share elsewhere. See config_dir for why two of those three are the same answer.

entries

entries(path: string) -> Result[Buf[string], IoError]

Every name in a directory, with . and .. left out.

The two dots are dropped because every caller drops them: a program listing a directory is asking what is in it, and one that genuinely wants to walk upwards has a path to build rather than a name to find. Leaving them in makes the ordinary case a filter written at every call site, and a recursive walk that forgets the filter does not terminate.

The names arrive in whatever order the filesystem keeps them, which is not sorted and is not stable between two listings of one directory. A program that wants an order applies one; there is no order here to be relied on by accident.

A name that is not UTF-8 makes the whole call answer InvalidUtf8, carrying the offset within that name. A POSIX name is bytes, and Linux will store any of them, so a program listing a directory it did not make can meet one. The whole call fails rather than the name being skipped, because a listing with a name silently missing is a wrong answer that looks like a right one – a copy that leaves a file behind, a clean-up that leaves it in place. A program that has to carry on through such a directory lists it with entry_bytes, which answers every name as the bytes it is.

entry_bytes

entry_bytes(path: string) -> Result[Buf[[]u8], IoError]

Every name in a directory as the bytes the filesystem holds, with . and .. left out and in the same unpromised order as entries.

This is entries for a directory whose names need not be text – the one a program did not make, on a filesystem that stores whatever bytes it was given. It never answers InvalidUtf8; a caller decodes each name itself with sysl.text.from_utf8, and decides what a name that does not decode should become. The bytes are a copy, so they outlive the listing.

executable

executable(path: string) -> bool

Whether this program may execute what path names, as POSIX’s access with X_OK answers it for the program’s own user and groups. It is the system’s answer rather than the bits’, so it can differ from Meta.executable: a file whose only execute bit is another user’s answers false here, and on a directory it is whether the program may search it. A program acting as user 0 may execute a file with any execute bit set. A path that is not there answers false.

exists

exists(path: string) -> bool

Whether there is anything at all at this path.

It answers false for a path that exists but sits under a directory the program may not search, which is the one way this differs from the question it looks like it is asking. That case cannot be told from absence without a second call whose answer would already be stale, and every caller that matters – one about to open the file – gets the truth from the open.

from_errno

from_errno(code: int) -> IoError

A number from the platform as the case it stands for: from_errno(2) is NotFound, and a code no case names is Other(code).

It is public so that a program calling C itself reports a failure the way this module does. An extern that fails leaves its number in errno; read straight after the call, this turns it into the same IoError the library’s own calls answer with, so e == NotFound means one thing whoever made the call. It is the table every IoError in the library comes through, not a second copy.

The chain is over errno values rather than over a name per platform because these are the codes that have been stable since V7 – ENOENT has been 2 on every Unix anyone has shipped – and the one that is not is not_empty above, which is why it is a call rather than a literal here.

get_xattr

get_xattr(path: string, name: string) -> Result[[]u8, IoError]

The value of the extended attribute name of what path names, following a symbolic link.

An attribute that is not there is NoAttribute, whatever the platform calls it, so a caller can tell “the file has no such attribute” from “there is no such file” (NotFound). A filesystem that keeps no attributes at all answers its own ENOTSUP as an Other: 45 on macOS, 95 on Linux. A name holding a zero byte is refused with Other(22), EINVAL, before anything is asked, since the platform would read it as the shorter name before the zero.

The value is the platform’s copy, and it is asked for twice: once for its size and once for the bytes. A value that grew between the two asks is asked for again rather than handed back cut short.

hard_link(existing: string, fresh: string) -> Result[unit, IoError]

A second name for a file that already exists, in the same filesystem.

The two names are equal afterwards – there is no original – and the file goes when the last of them does, which is what Meta.links counts. It fails across filesystems, and it fails on a directory, both of which are the kernel’s rules rather than this module’s.

home_dir

home_dir() -> Option[string]

Where the user’s home directory is, or None where the environment does not say.

HOME everywhere but Windows, which spells it USERPROFILE. A variable set to nothing counts as unset here, which is where this differs from sysl.env.get: an empty string is a truthful reading of an environment and is not a place, and every specification that mentions the case says to treat it as absent.

is_dir

is_dir(path: string) -> bool

Whether the path names a directory, asked of stat – which follows a symbolic link, as every other question here does. A directory the program may not read or search is still a directory; only a path stat cannot reach (missing, dangling, under an unsearchable directory) answers false. Where the target does not support stat at all, it asks whether the path opens as a directory instead.

is_file

is_file(path: string) -> bool

Whether the path names a regular file, asked of stat and so following a symbolic link. A directory, a device, a socket and a FIFO answer false, as does a path stat cannot reach. Where the target does not support stat at all, it answers whether something is there that does not open as a directory.

is_link(path: string) -> bool

Whether the path itself is a symbolic link. It follows nothing, so a link to a directory answers true here and is_dir answers true about the same path – the two are asking different questions and both answers are right.

link_get_xattr(path: string, name: string) -> Result[[]u8, IoError]

get_xattr about a symbolic link itself rather than what it points at. On a path that is not a link, the two are the same question.

link_list_xattrs(path: string) -> Result[Buf[string], IoError]

list_xattrs about a symbolic link itself.

link_metadata(path: string) -> Result[Meta, IoError]

The same, about the path itself – so a symbolic link is described rather than followed.

This is the only call in the module that can report a link at all. is_dir, exists and metadata all follow one silently, which is the right default and was until now the only behaviour available.

link_remove_xattr(path: string, name: string) -> Result[unit, IoError]

remove_xattr on a symbolic link itself.

link_set_times(path: string, accessed: Option[Instant], modified: Option[Instant]) -> Result[unit, IoError]

The same, on the path itself: a symbolic link’s own times are set, and what it points at is left untouched – link_metadata reads them back. A path that is not a link is set as set_times sets it, and a link that points nowhere is still a link whose times can be set.

link_set_xattr(path: string, name: string, value: []const u8) -> Result[unit, IoError]

set_xattr on a symbolic link itself, leaving what it points at untouched. macOS keeps attributes on a link; Linux refuses a user. attribute there with NotPermitted.

list_xattrs

list_xattrs(path: string) -> Result[Buf[string], IoError]

The names of every extended attribute of what path names, following a symbolic link, in the order the filesystem keeps them – which is not sorted and is not promised to be stable. A file with none answers an empty list.

The list holds what this process may see, not everything there is: Linux leaves out a trusted. attribute for a process without the privilege to read it, and macOS may hold names the system itself set (com.apple.provenance). A name that is not UTF-8 makes the whole call answer InvalidUtf8 at the offset within that name, as entries does for a directory.

make_dir

make_dir(path: string) -> Result[unit, IoError]

Makes one directory. The parent has to be there already: making a chain is a loop over path separators, and where a separator is is a question about paths rather than about the filesystem, which this module does not answer.

make_dir_all

make_dir_all(path: string) -> Result[unit, IoError]

Every directory on the path made, from the topmost one that is missing down.

A path that is already a directory is success, not AlreadyExists, which is the difference between this and a loop over make_dir and is what every caller of it wanted: the question being asked is “make sure this is there”, and a program that has to distinguish “I made it” from “it was there” is asking a question this cannot answer honestly anyway, since somebody else may have made it in between.

It tries make_dir(path) first and climbs with sysl.path.parent only when that answers NotFound, then retries, so each level is attempted once and the error is the one the operating system gave for the path the caller named. A file standing where a directory is needed above the leaf (make_dir_all("x/y") with x a regular file) reports NotADirectory, since mkdir answers ENOTDIR. A file standing at the leaf itself (make_dir_all("x") with x a regular file) reports AlreadyExists. Neither is silently accepted.

make_temp_dir

make_temp_dir(prefix: string) -> Result[string, IoError]

temp_dir under the name it had first; the two are one call.

map_file

map_file(path: string) -> Result[&Mapped, IoError]

The file at path, mapped read-only into memory. The file is closed before this answers; the mapping does not need it.

A directory is IsADirectory, a missing file NotFound, an unreadable one PermissionDenied. A file the platform cannot map – a pipe, a terminal – answers the platform’s own code as Other, and a target whose C library has no mmap answers “not supported on this target”.

metadata

metadata(path: string) -> Result[Meta, IoError]

Everything one stat answers about what a path names, following symbolic links.

A path that does not exist reports NotFound, which is the distinction a caller has to be able to make and the reason this answers a Result rather than an Option: “there is nothing there” and “the directory above it is not searchable” are different facts and lead to different programs.

open

open(path: string) -> Result[File, IoError]

The three ways a program opens a file, named for what it means rather than for the flags it becomes. open reads an existing file; create makes one, or empties one that was there; append writes at the end of whatever is there, making the file if it is not.

create, append and create_update take the permission bits a NEW file is born with, 0o666 by default, which the process umask narrows exactly as open(2) with O_CREAT does. A secret file asks 0o600 here and is owner-only from the moment it exists, with no window between creating and set_permissions. The mode applies only when the file is created: one that already exists keeps the mode it has. Bits above the twelve permission bits are dropped, as in set_permissions. A target with no permission bits ignores the mode.

open_dir

open_dir(path: string) -> Result[&Dir, IoError]

The directory at path, held open to reach what is beneath it.

A link as the last component of path is refused (refused_link()), and what is not a directory is NotADirectory. The components above it are the caller’s own path and are followed as any path is – /tmp is a link on macOS.

open_options

open_options() -> OpenOptions

The empty set of options: a file opened with it is read, and must already be there.

open_uncached

open_uncached(path: string, create: bool = false) -> Result[File, IoError]

A file opened for reading and writing that bypasses the operating system’s page cache: O_DIRECT on Linux, fcntl(F_NOCACHE) on macOS. A database that keeps its own buffer pool opens its files this way so a page is not held twice. create makes the file where it is missing and never empties one that exists.

Use it through read_at and write_at. The buffered read and write move odd amounts and so do not suit it. On Linux every transfer must have its buffer address, its offset and its length at a multiple of the device’s block size (512, in practice 4096), and a transfer that does not is Other(22) (EINVAL); macOS has no such rule. A filesystem that refuses the mode (tmpfs on older Linux kernels) answers Other(22) at the open. A target whose C library has neither mechanism answers “not supported on this target”.

open_update

open_update(path: string) -> Result[File, IoError]

A file opened for reading and writing, which the three above cannot express between them: each update mode is a different answer to “and what about what is already there”, and naming them apart is what keeps a caller from having to know that one fails on a missing file while the other empties one that exists.

open_with

open_with(path: string, options: OpenOptions) -> Result[File, IoError]

A file opened with exactly the options in options – see OpenOptions for what each asks of the operating system and what each failure is.

page_size

page_size() -> usize

The size in bytes of a page of memory, which a mapping is made and advised in.

pending_name

pending_name(target: string) -> string

A name beside target that no other call – in this process or in any other – will answer.

Write there, then hand both names to publish_file or publish_dir. It is the target with a suffix, so it is in the target’s directory and on the target’s filesystem, and a directory listing says which entry it was going to become.

publish_dir

publish_dir(pending: string, target: string) -> Result[unit, IoError]

Moves a finished directory from pending onto target – unless another writer got there first.

Losing that race is success, not failure. Two writers of one entry are building the same thing, and the one that finished first has already put a whole directory there; a rename refuses to replace a directory that holds anything, so the winner is never disturbed. The loser removes its own copy and answers as though it had written the one that is there. Only a rename that failed with no directory at target afterwards is reported.

An empty directory at target is replaced, which is rename(2)‘s rule and is not a race being lost: nothing was published there.

Clearing away the losing copy is remove_dir_all, which walks a tree over the hooks, so this exists wherever sysl.fs does.

publish_file

publish_file(pending: string, target: string) -> Result[unit, IoError]

Moves a finished file from pending onto target, replacing whatever was there.

A failure leaves nothing behind: the pending file is removed, so a full disk or a read-only directory leaves the previous entry and no debris beside it. The error is the rename’s, read before the removal could overwrite it. The permission bits travel with the rename, so a binary linked under the pending name is still one when it arrives.

read_bytes

read_bytes(path: string) -> Result[[]u8, IoError]

Every byte of the file.

The bytes are read straight into the storage that is handed back, which doubles whenever it fills: a read as large as the file’s own buffer goes to the descriptor directly, so a file is a few reads into its final home and a copy per doubling, never a byte at a time. It does not ask the file’s size first – that would reach a filesystem’s stat for a program that only reads, and a size is not a fact for a file being written while this reads it, or for anything whose length is only known when the read ends. The loop stops on the first empty read, and asks afterwards whether the reading ended badly – the two are separate questions, which is the split Reader was built around.

read_link(path: string) -> Result[string, IoError]

What a symbolic link points at, exactly as it was written – which may be relative, and may name nothing at all.

A path that is not a link reports Other(22), which is EINVAL: “this is not the kind of thing that has a target”. Ask is_link first where the difference matters.

read_text

read_text(path: string) -> Result[string, IoError]

The file as text, or InvalidUtf8 carrying the offset of the first byte that is not.

Bytes that are not UTF-8 are an error, not a trap, for the reason reference/errors.md gives for every failure that comes from outside the program: a file is input, and a program reading one it did not write cannot have ruled out the byte that breaks it. The offset is counted from the start of the file. A caller that wants the text anyway – replacing what does not decode, or treating the file as Latin-1 – reads read_bytes and decides for itself.

readable

readable(path: string) -> bool

remove_dir

remove_dir(path: string) -> Result[unit, IoError]

Removes a directory, which has to be empty. A directory with anything in it reports DirectoryNotEmpty – the one error code in the set whose number the two platforms disagree about, which is why error.sysl reads it through a call rather than a literal.

remove_dir_all

remove_dir_all(path: string) -> Result[unit, IoError]

A directory and everything under it removed.

The walk is post-order – a directory is emptied before it is taken – because rmdir refuses one that is not empty, which is the rule remove_dir states and this exists to work within rather than around.

A symbolic link is unlinked, not followed, which is the property that keeps this from deleting something outside the tree it was pointed at. entries says what is in a directory and is_dir follows links, so the test here is link_metadata – the one reading in the module that describes the path itself.

A path that is not there at all is success, except one holding a zero byte, which is Other(22): it names nothing the filesystem could lack. A caller tearing down after a failure should not have to know how far the failure got.

remove_file

remove_file(path: string) -> Result[unit, IoError]

Removes a file, and refuses a directory rather than removing it: unlink is the call that draws that line, where C’s own remove quietly does either. Two names for two intentions is what lets a program that meant one of them find out it had the other.

remove_xattr

remove_xattr(path: string, name: string) -> Result[unit, IoError]

The extended attribute name of what path names removed, following a symbolic link. One that is not there is NoAttribute – removing is not idempotent here, because the platform does not make it so and a caller that wants it to be matches the case away.

rename

rename(from: string, to: string) -> Result[unit, IoError]

Moves a path to another name, replacing whatever was at the destination.

It is one operation as far as anything watching is concerned when both paths are on the same filesystem, and it fails rather than copying when they are not – which is rename(2)‘s contract and worth knowing, since a program moving a file across devices has to read and write it itself.

rename_no_replace

rename_no_replace(from: string, to: string) -> Result[unit, IoError]

Moves a path to another name only where nothing is there, and reports AlreadyExists where something is – a file, a directory, a symbolic link, even a dangling one, and the file being moved itself, by the same path or a hard link, where rename would succeed doing nothing – leaving both untouched.

The check and the move are one operation in the kernel: renamex_np with RENAME_EXCL on macOS, renameat2 with RENAME_NOREPLACE on Linux. Checking with exists and then calling rename is a race that replaces whatever appears between the two, so a target with neither call answers “not supported on this target” rather than that. A Linux filesystem that cannot make the promise answers Other(22) (EINVAL). Otherwise it is rename: one step to anything watching, and a failure rather than a copy across filesystems.

set_current_dir

set_current_dir(path: string) -> Result[unit, IoError]

Moves the program. It is process-wide, which is the thing to know before reaching for it: a library that changes the working directory changes it for every thread and for every other library in the program, and puts it back only if it remembers to.

Prefer building an absolute path. This exists because a program that drives a build, or that is the shell-like thing at the top, genuinely needs it.

set_link_owner(path: string, owner: u32, group: u32) -> Result[unit, IoError]

The owner and group of path itself set to owner and group, as lchown(2): a symbolic link is given the ids and what it names keeps its own, which is the writing half of link_metadata‘s reading. unchanged for owner or group leaves that id as it is. Anything at path that is not a link is changed exactly as set_owner changes it, with set_owner‘s privilege rule: giving it away is NotPermitted to a program not acting as user 0. A path that is not there is NotFound; a target whose filesystem has no owners reports unsupported().

set_modified

set_modified(path: string, when: Instant) -> Result[unit, IoError]

The modification time of what path names – a file or a directory – set to when, and its access time with it, following a symbolic link. It is what makes “last used” a thing a program can record without writing to the file: a cache that evicts the least recently used entry touches what it hands out. A path that is not there reports NotFound; a target whose filesystem cannot be told a time reports unsupported().

Times are kept to the resolution of the filesystem, so reading back with metadata may round when.

set_owner

set_owner(path: string, owner: u32, group: u32) -> Result[unit, IoError]

The owner and group of what path names set to exactly owner and group – the two numbers Meta.owner and Meta.group read back, and sysl.process.user() and group() answer. A program changing only one passes unchanged for the other.

Giving a file away is privileged: a program not acting as user 0 is refused with NotPermitted, chown(2)‘s own rule. A symbolic link is followed, as set_permissions follows one. A target whose filesystem has no owners reports unsupported().

set_permissions

set_permissions(path: string, mode: u32) -> Result[unit, IoError]

The permission bits set to exactly what is given. It is not a mask to add: 0o644 means the file ends up 0o644 whatever it was, which is chmod(2)‘s own meaning and the one a program that read permissions() first is expecting.

set_times

set_times(path: string, accessed: Option[Instant], modified: Option[Instant]) -> Result[unit, IoError]

The access time and the modification time of what path names set, following a symbolic link – each to the Instant given, and left exactly as it was where None is given, which is what lets a program copying a file’s times carry one and not the other. set_times(p, Some(t), Some(t)) is set_modified(p, t).

Neither can be set to “now” by the kernel’s own clock here, because an Instant is a time and not an instruction: Some(sysl.time.now()) sets it by this program’s. The third time, changed, is not anyone’s to set: it moves to now on every call that changes anything.

A path that is not there reports NotFound – also where both are None, which changes nothing and still asks that the path be there, so the answer is the same on every platform. Times are kept to the resolution of the filesystem; an Instant is microseconds, which APFS, ext4, btrfs and xfs all keep exactly. A target whose filesystem cannot be told a time reports unsupported().

set_xattr

set_xattr(path: string, name: string, value: []const u8) -> Result[unit, IoError]

The extended attribute name of what path names set to value, following a symbolic link. The attribute is made where it is missing and its value replaced where it is not; an empty value is a value, and the attribute is there afterwards holding nothing.

Linux refuses a name outside a namespace it knows (Other(95), EOPNOTSUPP), and refuses a user. attribute on anything but a regular file or a directory (NotPermitted). A name holding a zero byte is Other(22), as for get_xattr.

size_of

size_of(path: string) -> Result[long, IoError]

How many bytes the file holds. It opens the file to ask, so it reports the same failures an open does – a missing file answers NotFound rather than zero, which is the distinction a caller sizing a buffer needs and the one a bare number could not carry.

space

space(path: string) -> Result[Space, IoError]

The size and the unused bytes of the filesystem that holds path, which may name a file or a directory anywhere on it and is followed through a symbolic link. Each number is a block count of POSIX’s statvfs times its fragment size, f_frsize, which is the unit those counts are in.

It is a reading, not a reservation: another program can take what was free before the next write lands, so a program that must not run out still handles the write’s own NoSpaceLeft. A path that is not there is NotFound; a target that cannot say reports unsupported().

symlink(target: string, link: string) -> Result[unit, IoError]

A symbolic link created at link, pointing at target.

target is not checked and does not have to exist. A dangling link is a legal thing to make and is sometimes the point – a package manager writes one before what it names has been unpacked. It is also stored as written: a relative target is resolved against the directory the link is in, every time it is followed, rather than against wherever the program was when it made the link.

temp_dir

temp_dir(prefix: string = "") -> Result[string, IoError]

A directory that did not exist a moment ago and that nobody else can take, made with mode 0700 inside temp_root(). Its name is prefix followed by six characters chosen to make it unique.

It is created, not merely named, which is the whole point: inventing a path and then making it leaves a gap between the two in which somebody else on a shared /tmp can take the name, and that somebody is not necessarily friendly. The prefix is for a human reading a directory listing and is not what makes the name unique.

Removing it is the caller’s, and remove_dir_all is the call: nothing here runs at the end of a scope that the scope did not say, so defer remove_dir_all(d) is the idiom.

A root that is not there answers NotFound, and one this process may not write in PermissionDenied. A prefix holding a / or a NUL is refused with Other(22), EINVAL, before anything is made: it would name something other than one entry of the root.

temp_file

temp_file(prefix: string = "") -> Result[(File, string), IoError]

A regular file that did not exist a moment ago and that nobody else can take, made inside temp_root() and answered open for reading and writing, with its path. Its name is prefix followed by six characters chosen to make it unique.

It is created and opened in one step – O_CREAT | O_EXCL, as mkstemp does – with mode 0600, so there is no moment at which the name is somebody else’s file or is readable by anyone but this user. Naming a file and then create-ing it would be the race temp_dir describes, with the added hazard that create follows a symbolic link somebody planted at the name. The process umask can narrow the mode further and never widens it.

The File closes when the last copy of it goes, like any other. The file itself stays: removing it is the caller’s, and defer remove_file(p) is the idiom – written after the binding, so it runs after the File is closed or dropped.

A root that is not there answers NotFound, and one this process may not write in PermissionDenied. A prefix holding a / or a NUL is refused as temp_dir refuses it.

temp_root

temp_root() -> string

The directory temporary files go in, which temp_dir and temp_file make things inside.

The rule, in order: TMPDIR where it is set and not empty; otherwise, on macOS, the per-user directory confstr(_CS_DARWIN_USER_TEMP_DIR) names (/var/folders/…/T), which is where Apple’s own NSTemporaryDirectory points and which only this user can write in; otherwise /tmp. Trailing slashes are dropped, so s"${temp_root()}/name" is the path the system will report back; / itself stays /.

It is read afresh at every call rather than once, so a program that sets TMPDIR for itself is answered with what it set. It is not checked: a TMPDIR naming nothing is answered as it is, and the failure is temp_dir‘s or temp_file‘s, where there is something to fail. A target whose hooks cannot answer, and a root whose name is not UTF-8 and so cannot be a string, are answered /tmp; temp_dir and temp_file report the second as InvalidUtf8 and leave nothing behind.

truncate

truncate(path: string, length: long) -> Result[unit, IoError]

A file cut to a length, or extended to one with zeroes. It makes nothing: a path that is not there reports NotFound rather than becoming an empty file.

Extending is truncate(2)‘s own behaviour and is worth knowing, since the name says only half of it: a length past the end of the file leaves a hole that reads as zeroes and that most filesystems do not store.

walk

walk(root: string) -> Walk

Everything at or under a path, the path itself first.

The root is reported whatever it is, so a walk of a plain file yields that one entry – which is what lets copy_dir_all be given either and do the right thing without asking first.

writable

writable(path: string) -> bool

write_bytes

write_bytes(path: string, bytes: []const u8, mode: u32 = file_mode) -> Result[unit, IoError]

Writes the bytes, replacing whatever was there and making the file if it was not.

mode is the permission bits a file this call makes is born with, exactly as create takes them: 0o666 by default, narrowed by the process umask, bits above the twelve dropped, ignored on a target with no permission bits. A file that is already there keeps its own mode – its contents are replaced, not the file. A failure answers what the open or the write said, the OS’s reason included, whichever mode was asked for.

write_bytes_atomic

write_bytes_atomic(path: string, bytes: []const u8, mode: u32 = file_mode) -> Result[unit, IoError]

Writes the bytes to path by way of a pending name, so a reader of path sees the whole of the previous file or the whole of this one and never a prefix of either.

On any failure – the write, the close or the rename – the pending file is removed and the first error is the answer, so path is exactly what it was before the call. A directory that is not there answers NotFound and leaves nothing anywhere.

mode is the permission bits the new file is born with, as write_bytes takes them (0o666 by default, narrowed by the umask). The pending file is created with them, so the file is never readable more widely than asked, not even under its pending name. Unlike write_bytes, a file already at path does not keep its mode: it is replaced by a new file, which has the mode asked for here.

write_text

write_text(path: string, text: string, mode: u32 = file_mode) -> Result[unit, IoError]

write_bytes for text, with the same mode.

write_text_atomic

write_text_atomic(path: string, text: string, mode: u32 = file_mode) -> Result[unit, IoError]

write_bytes_atomic for text, with the same mode.

Types

Advice

enum Advice
    Normal
    Random
    Sequential
    WillNeed
    DontNeed

How a mapped range is about to be read, for Mapped.advise.

Dir

struct Dir
    private handle: int

A directory open for reaching what is beneath it, and only that.

Every path handed to it is relative to it and stays inside it. A symbolic link at any component is refused – the last one or one above it, pointing out of the directory or back into it. An absolute path is refused too, and so is a .. that would climb above the directory (.., a/../..).

A .. that stays inside is accepted, by lexical collapse: before the kernel is asked, every path – both paths of a rename – has its . components dropped and each x/.. removed, so a/b/../c is a/c. This is sound only because links stay refused: with no link anywhere, a/b/.. can only mean a, and the kernel never walks b, so nothing can be moved or swapped under the path between a check and the use. It differs from what the kernel would answer in one way: a/missing/../c reaches a/c instead of failing with NotFound. A path ending in . or .. keeps a trailing /, so it must still name a directory; a path with neither component is handed on exactly as written, repeated and trailing separators included.

A path that collapses to nothing (., a/..) names the directory itself. link_metadata and exists describe it, make_dir answers AlreadyExists, and open and open_with asking only to read hand back a read-only handle on the directory; an open asking to write or create answers whatever the kernel answers for a directory (IsADirectory). The calls that need a name beneath it – remove_file, remove_dir, either path of a rename – refuse it with an error names_itself() recognises.

Each refusal is an IoError that refused_link(), escaped() or names_itself() recognises; every other failure is the ordinary one (NotFound, PermissionDenied, …).

It closes itself when its last reference goes. A File opened through it is a descriptor of its own, and stays open after the directory is gone.

MemberSignatureDescription
fdfd(self) -> intThe descriptor, lent for a call this module does not make; the directory still closes it.
openopen(self, path: string) -> Result[File, IoError]The five ways a file is opened, as sysl.fs.open, create, append, open_update and create_update open one, with path beneath this directory.
createcreate(self, path: string, mode: u32 = file_mode) -> Result[File, IoError]
appendappend(self, path: string, mode: u32 = file_mode) -> Result[File, IoError]
open_updateopen_update(self, path: string) -> Result[File, IoError]
create_updatecreate_update(self, path: string, mode: u32 = file_mode) -> Result[File, IoError]
open_withopen_with(self, path: string, options: OpenOptions) -> Result[File, IoError]A file opened with exactly the options in options, as sysl.fs.open_with opens one and with the same errors – create_new‘s AlreadyExists and truncate‘s Other(22) without write among them – with path beneath this directory and refused exactly as open refuses it.
read_bytesread_bytes(self, path: string) -> Result[[]u8, IoError]The whole-file functions, as sysl.fs.read_bytes, read_text, write_bytes and write_text do them and with the same errors (the OS’s reason for a failed write included), with path beneath this directory and refused exactly as open and create refuse it.
read_textread_text(self, path: string) -> Result[string, IoError]
write_byteswrite_bytes(self, path: string, bytes: []const u8, mode: u32 = file_mode) -> Result[unit, IoError]
write_textwrite_text(self, path: string, text: string, mode: u32 = file_mode) -> Result[unit, IoError]
link_metadatalink_metadata(self, path: string) -> Result[Meta, IoError]What is at path, described as sysl.fs.link_metadata describes it: a link as the last component is reported as a link (is_link()), never followed.
existsexists(self, path: string) -> boolWhether anything is at path, a link included.
remove_fileremove_file(self, path: string) -> Result[unit, IoError]Removes the file at path.
make_dirmake_dir(self, path: string) -> Result[unit, IoError]Makes one directory at path, as sysl.fs.make_dir does: the parent has to be there already, and it is born with 0o777 narrowed by the umask.
remove_dirremove_dir(self, path: string) -> Result[unit, IoError]Removes the directory at path, which has to be empty, as sysl.fs.remove_dir does: DirectoryNotEmpty where it is not, NotADirectory for a file or a link there – a link is never followed.
renamerename(self, from: string, to: string) -> Result[unit, IoError]Moves from to to, both beneath this directory, replacing whatever was at to, as sysl.fs.rename does.
rename_no_replacerename_no_replace(self, from: string, to: string) -> Result[unit, IoError]rename only where nothing is at to, as sysl.fs.rename_no_replace does it: the check and the move one operation in the kernel (renameatx_np with RENAME_EXCL on macOS, renameat2 with RENAME_NOREPLACE on Linux, each between the two paths’ directories), AlreadyExists where anything is there – a link, even a dangling one, and the file being moved itself – with both left untouched, and “not supported on this target” where neither call exists.

Entry

struct Entry
    path: string
    depth: usize
    meta: Meta

One entry a walk reported: where it is, how far down, and one reading of what it is.

The Meta is a link_metadata, so a symbolic link describes itself rather than whatever it points at. That is what is_dir on this answers about, and it is why a walk never follows one.

The depth is from the root the walk was given, which is itself depth zero. A caller reproducing the tree somewhere else wants sysl.path.relative_to rather than this, but a caller that only needs to know how deep it has got – a printer indenting, a search bounding itself – would otherwise have to count separators.

MemberSignatureDescription
is_diris_dir(self) -> boolWhether this is a directory the walk will descend into – so a link to one answers false.
is_linkis_link(self) -> boolWhether this is a symbolic link, which a walk reports and does not follow.

File

struct File
    inner: &FileState

A file that is open, or that was.

It closes itself: when the last copy of a File goes – out of scope, out of a Buf, with the struct that held it – what is still buffered is handed over and the descriptor is closed, as Rust’s File does. close is still there, and is what a program calls when it wants to know the answer: a full disk reports when the buffer is handed over, and a destructor has nobody to tell. defer f.close() remains a correct way to write that, and is no longer needed to stop a leak.

Every copy shares one open file. Closing any of them closes it for all, and saying it twice is harmless rather than a use-after-free, which is the mistake a value type would otherwise make easy. While any copy lives the descriptor stays open.

MemberSignatureDescription
closedclosed(*self) -> bool
fdfd(self) -> Result[int, IoError]The descriptor the file reads and writes through, for a call this module does not make.
into_raw_fdinto_raw_fd(*self) -> Result[int, IoError]The descriptor, given rather than lent: the file lets go of it, and closing it is from now on the caller’s to do – Rust’s into_raw_fd.
mapmap(*self) -> Result[&Mapped, IoError]The file’s bytes, mapped read-only into memory rather than read – map_file, for a file that is already open.
map_mutmap_mut(*self, len: usize = …) -> Result[&MappedMut, IoError]The file’s bytes mapped readable and writable and shared, so a write through bytes() reaches the file.
sync_datasync_data(*self) -> Result[unit, IoError]Hands what is buffered over and asks the device to keep the file’s contents, returning once it has – sync without the metadata a reader does not need (fdatasync on Linux, which skips an unchanged modification time).
full_syncfull_sync(*self) -> Result[unit, IoError]The strongest durability the platform offers: what is buffered is handed over and the device is made to empty its own write cache.
locklock(self, kind: LockKind) -> Result[unit, IoError]Takes an advisory lock on the whole file, waiting until no other open file holds one that conflicts: a Shared lock waits out an Exclusive one, and an Exclusive lock waits out both.
try_locktry_lock(self, kind: LockKind) -> Result[unit, IoError]lock without the wait: the lock is taken now, or the answer is an IoError whose would_block() says another open file holds one that conflicts, and nothing new is held.
unlockunlock(self) -> Result[unit, IoError]Gives up the lock this file holds, of either kind, handing over what is buffered first, as close does: bytes written under the lock are in the file before anybody waiting for it gets in.
flushflush(*self) -> Result[unit, IoError]Hands over what is buffered.
closeclose(*self) -> Result[unit, IoError]Releases the descriptor, handing over what is still buffered.
telltell(*self) -> Result[long, IoError]Where the next read or write will happen, in bytes from the start.
seekseek(*self, to: long) -> Result[unit, IoError]Moves to an absolute offset, which also clears the end-of-file mark.
sizesize(*self) -> Result[long, IoError]How many bytes the file holds.
at_endat_end(*self) -> boolWhether a read has already run off the end.
truncatetruncate(*self, length: long) -> Result[unit, IoError]The file cut to a length, or extended to one with zeroes – the one thing this surface could not do, having seek and size and no way to change what is there.
set_permissionsset_permissions(*self, mode: u32) -> Result[unit, IoError]The twelve permission bits of this open file set to mode – fchmod(2) on the descriptor, so it changes the file this handle holds whatever the path now names.
read_failureread_failure(*self) -> Option[IoError]What the file latched when a read failed, as the same IoError – the system’s own wording and errno – that a whole-file read answers, or None while failed is false.

FileState

struct FileState
    fd: int
    bad: bool
    shut: bool
    fault: int
    ended: bool
    erred: bool
    held: []u8
    at: usize
    filled: usize
    pending: usize

The handle itself, and everything that is true of it beyond the descriptor.

It is a struct of its own – rather than these fields sitting directly in File – because of what File has to survive being copied. A struct is a value here, so a File handed to a function is a second File, and if it held the descriptor and the buffer directly then closing either would leave the other writing into a descriptor that was released, and the two would disagree about what was buffered. Every copy sharing one FileState is what makes close answerable at all: it is written once, and every copy sees it. It is also what gives the descriptor one point of death: the last copy going is the state’s last reference going, and its destructor closes what nobody closed.

The buffer holds one direction at a time. Reading, held[at..<filled] is what arrived and has not been handed out; writing, held[0..<pending] is what was written and has not been handed over. fault is the status of the last thing that went wrong (a code, negated, as a hook answers it), zero while nothing has, and ended says a read has run off the end since the position was last set.

IoError

enum IoError
    NotFound
    PermissionDenied
    AlreadyExists
    NotADirectory
    IsADirectory
    DirectoryNotEmpty
    TooManyOpenFiles
    NoSpaceLeft
    Interrupted
    NotOpen
    NotPermitted
    InvalidUtf8(offset: usize)
    NoAttribute
    Other(code: int)

Why a filesystem operation did not happen.

MemberSignatureDescription
codecode(self) -> intThe number this came from, so a program can report or compare one the set does not name.
messagemessage(self) -> stringA sentence, in the terms the operation was asked in rather than in C’s.
refused_linkrefused_link(self) -> boolWhether a Dir refused this path because a component of it is a symbolic link – the last one or any above it, whether the link points inside the directory or out of it – or open_with asked nofollow refused it because its last component is one.
escapedescaped(self) -> boolWhether a Dir refused this path because it leads out of the directory: an absolute path, a .. component, or the kernel finding a way out.
names_itselfnames_itself(self) -> boolWhether a Dir refused this path because it names the directory itself – ., or a path such as a/.. that collapses to nothing – where the call needs a name beneath it: a name to remove, or either end of a rename.
would_blockwould_block(self) -> boolWhether the call would have had to wait – what File.try_lock answers when another open file holds a lock that conflicts.

Kind

enum Kind
    Regular
    Directory
    Symlink
    Special(bits: u32)

What a filesystem entry is, beside what is in it.

The three a program branches on are named and everything else is Special carrying the raw type bits, for the same reason IoError names ten codes and carries the rest: a table of every device flavour is one nobody could keep current, and a program that genuinely cares about a socket is already reading the number. Special is POSIX’s own word for what is left – a fifo, a socket, a character or block device.

Regular rather than File, and Special rather than Other, and both are about COLLISION rather than about taste. A variant is a name of its module, reached unqualified, so File here would be a second answer for the name sysl.fs.File – the open-file handle, which is what a program means by it – and Other a second answer for IoError.Other, which every program matching on a filesystem error already writes bare. Neither is refused at the declaration; both make an ordinary use of the older name ambiguous, one program away.

MemberSignatureDescription
is_diris_dir(self) -> boolSo that k == Directory reads as itself.
namename(self) -> stringThe word for what this is.

LockKind

enum LockKind
    Shared
    Exclusive

Which lock File.lock and File.try_lock take: one any number of open files may hold together (Shared, for readers), or one no other open file may hold beside it (Exclusive, for a writer).

Mapped

struct Mapped
    private at: *u8
    private n: usize

The bytes of one file as they were when it was mapped, from map_file or File.map.

Dropping the last reference unmaps it, so it is held as a &Mapped like any other type with a destructor. bytes() is a view borrowed from it (reference/memory.md § A view borrowed from its receiver): the compiler refuses a view that would outlive the mapping it reads.

An empty file maps nothing – the operating system refuses a mapping of no bytes – and answers an empty view.

MemberSignatureDescription
lenlen(self) -> usizeHow many bytes are mapped: the file’s size when it was mapped.
is_emptyis_empty(self) -> bool
bytesbytes(&self) -> []const u8The whole file, read-only.
adviseadvise(self, advice: Advice, from: usize = 0, len: usize = …) -> Result[unit, IoError]Tells the operating system how len bytes from offset from are about to be used; len left out means to the end of the mapping.

MappedMut

struct MappedMut
    private at: *u8
    private n: usize

A file’s bytes mapped shared and writable, from File.map_mut: a write through bytes() is a write to the file.

Nothing is promised to be on the device until flush. The system writes dirty pages back when it chooses, and a program that exits or drops the mapping loses nothing the system has accepted (it stays in the page cache and reaches the file), but only flush – and File.sync_data or full_sync after it, for power-loss durability – says the bytes are out. The mapping is as long as the file was when it was made and does not follow it: cutting the file shorter underneath makes a read of a page past the new end a signal. Dropping the last reference unmaps it; hold it as a &MappedMut.

MemberSignatureDescription
lenlen(self) -> usize
is_emptyis_empty(self) -> bool
bytesbytes(&self) -> []u8The whole mapping, writable.
flushflush(self, from: usize = 0, len: usize = …) -> Result[unit, IoError]Writes len bytes from offset from (len left out: to the end) to the file and returns once they are there – msync(MS_SYNC).
flush_asyncflush_async(self, from: usize = 0, len: usize = …) -> Result[unit, IoError]Schedules the same write-back and returns at once (msync(MS_ASYNC)).

Matching

struct Matching
    private inner: Walk
    private root: string
    private pattern: string

A walk with a glob over it – what Walk.matching answers, and not a thing to construct.

It holds the root separately from the walk because the walk’s own is private to it and the pattern is matched against a relative path. That is one string per filtered walk rather than per entry, since relative_to is what allocates here and it allocates once per entry either way.

Meta

struct Meta
    size: long
    mode: u32
    links: u64
    owner: u32
    group: u32
    inode: u64
    device: u64
    modified: Instant
    accessed: Instant
    changed: Instant
    created: Option[Instant]

Everything one stat answers, in one value.

One call rather than several is the point. Asking separately whether a path is a directory, how big it is and when it changed is three trips into the kernel and three chances for the answer to be about three different files – something can be replaced between them. A Meta is one reading of one entry.

The times are Instants, so sysl.time turns them into a date with nothing here knowing about calendars. That costs the nanoseconds the platform reports: an Instant is microseconds, which is the library’s resolution everywhere and is finer than any filesystem here records reliably.

MemberSignatureDescription
kindkind(self) -> Kind
permissionspermissions(self) -> u32The permission bits alone – the low twelve, which are the nine rwx plus setuid, setgid and the sticky bit.
is_fileis_file(self) -> bool
is_diris_dir(self) -> bool
is_linkis_link(self) -> boolWhether the entry itself is a symbolic link, which only link_metadata can ever answer true to: metadata follows links, so what it describes is never one.
executableexecutable(self) -> boolWhether the entry is a regular file with any of its three execute bits set – the owner’s, the group’s or everyone else’s.
same_filesame_file(self, other: Meta) -> boolWhether two readings name the same file, which is the inode and the device together and is not the path.

OpenOptions

struct OpenOptions
    private[fs] flags: u32
    private[fs] bits: u32

What open_with is asked to do, said one option at a time: open_options() is the empty set, and each member answers the same set with one more thing asked of the open, so a set reads as a chain – open_options().write().create_new().mode(0o600). It is the shape a Walk has, and a value rather than a list of parameters so that a program can build one set and open several files with it.

Every option reaches the operating system or the open fails; none is dropped quietly:

  • read and write say how the file is used. Asking neither reads it, as open(2) does with no access mode.
  • append writes at the end of whatever is there at each write, and implies write.
  • truncate empties a file that is there. It needs write: an open asking it without is refused with Other(22) (EINVAL) before the call, because POSIX leaves O_TRUNC on a file opened only for reading unspecified.
  • create makes the file where it is missing (O_CREAT).
  • create_new makes the file and fails with AlreadyExists where anything is there, a symbolic link included, dangling or not (O_CREAT | O_EXCL): the check and the making are one step, which is what a lock file or a never-overwrite save needs and what exists followed by create is not.
  • sync makes every write wait until the data and the metadata needed to read it back are on the device (O_SYNC); dsync waits for the data, and for the metadata only where reading the data back needs it (O_DSYNC, or O_SYNC where a C library has no O_DSYNC).
  • nofollow refuses a symbolic link at the last component of the path (O_NOFOLLOW): the error answers refused_link(). A link in a directory above the last component is still followed – confining a whole path is Dir‘s work – and a chain of links that loops above it is refused the same way, since the kernel gives the two one code.
  • mode is the permission bits a file this open creates is born with, 0o666 unless asked, which the process umask narrows exactly as it does for create. It applies only when the file is created; bits above the twelve permission bits are dropped.

A target whose C library has no O_SYNC or no O_NOFOLLOW answers “not supported on this target” to an open asking for it.

MemberSignatureDescription
readread(self) -> OpenOptions
writewrite(self) -> OpenOptions
appendappend(self) -> OpenOptions
truncatetruncate(self) -> OpenOptions
createcreate(self) -> OpenOptions
create_newcreate_new(self) -> OpenOptions
syncsync(self) -> OpenOptions
dsyncdsync(self) -> OpenOptions
nofollownofollow(self) -> OpenOptions
modemode(self, bits: u32) -> OpenOptions

Space

struct Space
    total: u64
    free: u64
    available: u64

How big a filesystem is and how much of it is unused, in bytes – one statvfs reading.

free and available are two answers because a filesystem keeps a reserve: free is every unused byte, and available is the part of it a program not acting as user 0 may take, which is the one a program checking whether its write will fit compares against. So available <= free <= total on every filesystem, and the two are equal where nothing is held back.

Walk

struct Walk
    private stack: Buf[Frame]
    private root: string
    private started: bool
    private up: bool
    private open_next: Option[Entry]
    private pruned: bool

A cursor over a directory tree, reporting the root and then everything under it.

The default order is parents first, which is what a caller reproducing a tree needs: a directory has to exist before anything can be written into it. bottom_up reverses that for the callers that need the opposite, remove_dir_all being the one in this file – rmdir refuses a directory that is not empty.

A failure is reported as an item rather than ending the walk, so a directory that cannot be read is one Err and the walk carries on with what is left. That is the axis remove_dir_all and a best-effort cleanup disagree about, and neither answer is now the library’s: ? in the loop body makes the first Err fatal, and ignoring it makes the walk best effort.

An entry that disappears while the walk is under way is absent, not a failure. A directory is listed once and its names are read one at a time afterwards, so another process may remove one in between – a lock directory, a temporary file. Such a name is skipped, and a directory removed after it was reported is walked as an empty one. A root that does not exist when the walk starts is still an Err, since that is a path the caller named rather than one the walk found.

MemberSignatureDescription
bottom_upbottom_up(self) -> WalkThe same walk, reporting a directory after everything under it.
skip_dirskip_dir(*self) -> unitDo not descend into the directory just reported.
matchingmatching(self, pattern: string) -> MatchingThe same walk, reporting only the entries whose path matches a glob.

Implementations

Display for IoError

impl Display for IoError

So that print(e) and f"$e%s" say the sentence rather than the shape of the value.

Display for Kind

impl Display for Kind

So that a kind prints as the word rather than as a number, and Special says what it is carrying: a program reporting what it found in a directory has one thing to print, and the alternative is a match at every such site.

Drop for Dir

impl Drop for Dir

The descriptor closed when the last reference goes. A failure closing it has nobody to tell.

Drop for FileState

impl Drop for FileState

The descriptor closed when the last File sharing it goes, unless close or into_raw_fd already gave it up. What is still buffered is handed over first, and a failure doing either is not reported: a destructor has nobody to report it to (sysl.Drop), so a program that cares whether its output arrived calls close and reads the answer.

Drop for Mapped

impl Drop for Mapped

Drop for MappedMut

impl Drop for MappedMut

Eq for IoError

impl Eq for IoError

So that a caller can say e == NotFound rather than e.code() == 2.

The enum’s own docstring is what asks for this: it says the cases are named so that a program acting on why can match rather than compare against a number, since “a comparison against a number is a guess that compiled” – and without an Eq the only comparison available was exactly that. This module’s own test wrote assert_eq(e.code(), 2) for want of it.

A payload is why it has to be written out. An enum no variant of which carries anything gets == on its discriminant for free; Other carries a code, so this one does not.

It compares on code(), which makes Other(2) equal to NotFound – deliberately, because they are the same condition wearing two spellings, and from_errno never produces the first. Comparing on the shape instead would make an error that came from a platform sysl does not have a named case for unequal to itself after a round trip through a number.

InvalidUtf8 is the exception, because its payload is not a code: two of them are equal when they stopped at the same byte, and one is never equal to anything else – from_errno cannot produce it, so there is no second spelling for it to agree with, and comparing it on code() would make InvalidUtf8(3) == InvalidUtf8(40).

Eq for Kind

impl Eq for Kind

Fallible for File

impl Fallible for File

Whether anything has gone wrong on this file since it was opened. It latches, so it is worth asking once after a run of writes rather than after each – which is the whole reason the surface reports this way (reference/errors.md § The third shape: a latch).

It is written once, here, and that is what makes the two impl blocks below answerable. A failed declared by Reader and another declared by Writer would be two members of one name on one type – allowed, but a call could not say which it meant, since failed takes no arguments and a program that reads and writes a file has both traits in scope. Both requiring Fallible instead leaves this the single answer each of them reaches.

Iterate for Matching

impl Iterate for Matching

Iterate for Walk

impl Iterate for Walk

Positioned for File

impl Positioned for File

A file is a positioned store too (sysl.io.ReadAt, sysl.io.WriteAt), so a codec or a filesystem written against those reads and writes it with no adapter.

extent is size, as the unsigned count the traits speak in.

ReadAt for File

impl ReadAt for File

Reading at an offset does not move the position*, so it mixes freely with read and write: it is the platform’s pread, past the buffer. Anything still buffered for writing is handed over first, so a read answers with every byte the program has written; what was read ahead stays where it is, since nothing it holds has changed.

An offset past what a long can hold is refused as the platform refuses one, with EINVAL.

Reader for File

impl Reader for File

Reading bytes out of a file is the Reader of sysl.io, whole and unmodified, which is what lets lines(&f) work over a file with nothing here knowing about lines.

An empty answer means the end of the input and nothing more. Whether the input ended badly is what failed reports, and the two are separate questions because a caller that does not care should not have to ask – the same split FdReader makes.

It fills into unless the file ends first, as C’s fread did, so a short answer is the end of the file or a failure and never merely a slow device.

WriteAt for File

impl WriteAt for File

Writing at an offset does not move the position either.* It is the platform’s pwrite, and what was buffered either way is settled first: pending writes are handed over so they cannot land on top of this one later, and what was read ahead is given up, since this write may have changed it.

On Linux a file opened with append puts a positioned write at the end regardless of the offset – a documented defect of the platform’s pwrite, kept here rather than hidden.

sync hands over what is buffered and then asks the device to keep it (fsync), returning once it has.

Writer for File

impl Writer for File

And writing them is the Writer of library/core.md § What is in it, so everything that renders into a sink renders into a file. It latches rather than returning, which is what keeps f.write(b) a statement.

Search

Esc
↑↓ to navigate ↵ to open Esc to close