Trusted. File
(Cure Standard Library v0.38.0)
View Source
Filesystem access for the trusted (unproved) standard library.
Why this module exists
A file read cannot be proved total: the file may be missing, unreadable, or
not valid UTF-8. Std.* therefore has no file I/O, and every program that
needs some used to re-declare the same four @externs — and, in doing so,
re-declare the same unsoundness:
fn read_file(path: String) -> String =
let chars = binary_to_chars(elem(2, raw_read_file(characters(path))))
Std.String.from_characters(chars)read_file/1 cannot fail in its type, so it fails at runtime instead: a
missing file raises badarg from :erlang.element/2, and nothing at the
call site suggests it might. This module writes the same operation with the
failure in the type, exactly once.
The trust contract
This module satisfies the four rules every Trusted.* module must meet
(see docs/TRUSTED.md):
- Total surface. No public function returns a bare
TupleorBinary. Every fallible operation returnsResult(T, FileError). Partial projections arelocaland guarded: a reply's shape is established by:erlang.tuple_size/1and its tag by a comparison on anAtom-typed value before any field is projected, so nobadargcan escape.exists?/1anddirectory?/1areBoolbecause the question they answer has no failure mode. - Declared boundary. Every
@externa public function reaches carries a## Trust:block naming the OTP contract relied on. - No proof claims. Nothing here is a proof, and nothing pretends to be one.
- Reviewable axiom set.
cure audit trust Trusted.Filesnapshots the reachable externs; adding one requires a reviewed snapshot change.
Examples
mod ReadExample
use Std.Result
use Trusted.File
fn contents(path: String) -> String =
match read(path)
Ok(text) -> text
Error(_) -> ""mod ReadErrorExample
use Std.Result
use Trusted.File
use Trusted.Error
fn explain(path: String) -> String =
match read(path)
Ok(_) -> "found"
Error(NotFound()) -> "no such file"
Error(other) -> describe(other)
Summary
Types
The kind of filesystem object a path names.
Functions
Append text to path, creating it if absent.
Map OTP's :file type atom onto FileType.
Create path's parent, then retry path itself.
Project the device out of a :file.open/2 reply.
Project the entry list out of a :file.list_dir/1 reply.
Turn a :file.list_dir/1 payload into sorted String entries.
Project {error, Reason} out of a :file reply.
Project the size field out of a :file.read_file_info/1 reply.
Project the type field out of a :file.read_file_info/1 reply.
Decode a :file.read_file/1 reply into Result(Binary, FileError).
Read the size field of an already-established 2-tuple reply.
Decode a UTF-8 Binary into the nominal String.
Decode a :file reply that either is the bare atom ok or is
{error, Reason}.
true when path names an existing directory.
Preserve the operation's original failure even if best-effort cleanup fails.
Every segment except the last, preserving order.
Convert each charlist entry to a String, in reverse order.
true when path names an existing regular file.
The :file type of path.
Write and close only the descriptor this invocation created. Rename is reached only after both succeeded; every failure cleans up our own sibling.
Project the type field out of a #file_info{} record.
Insert s into an already-sorted list, preserving order.
true when path begins with a separator.
Join segments with /, starting from acc.
The entries of a directory, excluding . and .., sorted.
Create a directory and every missing parent.
Create path, falling back to creating its parent first.
Open path in raw binary append mode.
The parent directory of path.
Publish a closed, complete staging file. A rename failure leaves the old target intact and removes the staging file rather than leaking it.
Trust: :unicode.characters_to_list/1 for the charlist arm. Declared separately at
List(Char) so the discriminator's result can be handed to
Std.String.from_characters/1 without a cast: the guard has already
established the shape.
Trust: :unicode.characters_to_list/1 answers a charlist for valid UTF-8,
or {error, Converted, Rest} / {incomplete, Converted, Rest} for invalid
or truncated input. Declared at Any because the failure arms are tuples,
not lists; decode_text/1 discriminates with :erlang.is_list/1 before
touching the value.
Trust: :file.close/1 answers ok or {error, Reason}.
Trust: :file.delete/1 answers ok or {error, Reason}. A missing file
answers {error, :enoent} rather than ok.
Trust: :erlang.element/2 on the payload position of a :file.list_dir/1
reply. Declared at List(List(Char)) — the shape OTP documents for the
payload — because the caller has already established the 2-tuple shape and
the :ok tag, so this arm is only reached for a real directory listing.
Trust: :erlang.element/2 is 1-based and raises badarg when the index is
out of range. Every call below is guarded by a raw_tuple_size/1 check, so
the index is always in 1..2.
Trust: :erlang.element/2 as raw_element/2, but for the reply's tag position, which holds
the atom :ok or :error.
Trust: :erlang.element/2 on the reason position of a {error, Reason}
reply. Declared at Tuple for the reply (every :file reply is a 2-tuple)
and Atom for the reason, which is what every POSIX reason is. The caller
has already established the 2-tuple shape, so the index is in range.
Trust: :erlang.element/2 on the reason position of a {error, Reason}
reply whose static type is the erased Atom carrier.
Trust: :erlang.element/2 on the payload position of a
:file.read_file_info/1 reply. Declared at Tuple because the payload is
the opaque #file_info{} record, which is a tuple. The caller established
the reply's 2-tuple shape and its :ok tag, so index 2 is in range.
Trust: :erlang.is_integer/1 is a pure type test; it never raises.
Trust: :erlang.is_list/1 is a pure type test; it never raises.
Trust: :erlang.is_tuple/1 is a pure type test; it never raises. Used to
discriminate the {error, Reason} arm of a :file reply from the ok
atom before projecting the reason.
Trust: :file.list_dir/1 answers {ok, Filenames} or {error, Reason},
where Filenames are charlists without a directory prefix. We rely on
the 2-tuple shape and on the payload being a list.
Trust: :file.make_dir/1 answers ok or {error, Reason}. :eexist is
reported rather than swallowed, which is what lets mkdir_p/1 distinguish
"already there" from a genuine failure.
Trust: :file.open/2 answers {ok, IoDevice} or {error, Reason}.
append/2 uses [:append, :raw, :binary]; atomic writes use
[:write, :exclusive, :raw, :binary]. Exclusive creation fails with
:eexist rather than opening any existing file or following its symlink.
The device speaks raw binaries rather than going through the io protocol.
Declared at Tuple: both arms are 2-tuples.
Trust: :file.read_file/1 answers {ok, Binary} on success or
{error, Reason} on failure, where Reason is a POSIX atom.
OTP kernel reference, file module. We rely on: (a) the 2-tuple shape,
(b) Reason being an atom.
Trust: :file.read_file_info/1 answers {ok, FileInfo} or
{error, Reason}, where FileInfo is an opaque #file_info{} record.
We rely on: the 2-tuple shape and the record's field order, which OTP
documents as stable (size at position 2, type at position 3).
Trust: :file.rename/2 answers ok or {error, Reason}. Rename within a
directory is atomic on every POSIX filesystem, which is what makes
write/2 all-or-nothing.
Read the size field out of a #file_info{} record.
Trust: :erlang.tuple_size/1 raises badarg on a non-tuple. Only ever
called on a value :file.read_file/1 produced, which is always a tuple.
Trust: :erlang.unique_integer/1 with [:positive, :monotonic] returns
a positive integer unique within this VM. It is NOT globally unique:
exclusive file creation, not this suffix, establishes staging ownership
across VMs. Collisions are retried with a bounded budget.
Trust: :file.write/2 on a raw device answers ok or {error, Reason}.
Read a whole file as UTF-8 text.
Read a whole file as raw bytes, with no decoding.
Delete a file.
Reverse a list of strings.
File size in bytes.
Insertion sort over String, using Std.String's Comparable instance.
Try at most attempts exclusive sibling names. A failed open does not
confer ownership, so its path must never be cleaned up.
true when path is a filesystem root that cannot have a parent.
Attempt one exclusive open. Keep collision handling separate from naming: an existing file or symlink belongs to someone else, even on the last try.
Write text to path, replacing it atomically.
Write bytes to device, then close it.
Write raw bytes to path, replacing it atomically.
Types
enum FileType
Regular
Directory
Symlink
Other
The kind of filesystem object a path names.
A closed ADT rather than OTP's raw atom, so exists?/directory? match on
constructors instead of comparing atoms — and so an unfamiliar :file type
is carried as Other(atom) rather than silently comparing false to
everything.
Functions
fn append(path: String, text: String) -> Result(Unit, FileError)
Append text to path, creating it if absent.
Unlike write/2 this is NOT atomic: append is a single :file.write/2 on
a device opened in :append mode, which the kernel serialises per write.
Making it atomic would require reading and rewriting the whole file, which
changes the operation's cost class for no benefit -- a caller that needs
all-or-nothing uses write/2.
Examples
mod AppendDocExample
use Std.Result
use Trusted.File
use Trusted.Error
fn log_line(path: String, line: String) -> String =
match append(path, line)
Ok(_) -> "appended"
Error(reason) -> describe(reason)
fn classify_type(kind: Atom) -> FileType
Map OTP's :file type atom onto FileType.
Declared before its callers: Cure resolves names in declaration order, so a helper used by an earlier function must itself be earlier.
fn create_parent_then(path: String) -> Result(Unit, FileError)
Create path's parent, then retry path itself.
fn decode_device(path: String, opened: Tuple) -> Result(Atom, FileError)
Project the device out of a :file.open/2 reply.
fn decode_dir_listing(path: String, listing: Tuple) -> Result(List(String), FileError)
Project the entry list out of a :file.list_dir/1 reply.
fn decode_entries(payload: List(List(Char))) -> Result(List(String), FileError)
Turn a :file.list_dir/1 payload into sorted String entries.
The payload is declared at the type :file.list_dir/1 documents for it —
a list of charlists. decode_dir_listing/2 has already established the
surrounding 2-tuple shape, so the destructuring here is total.
fn decode_error_tuple(reply: Atom) -> Result(Unit, FileError)
Project {error, Reason} out of a :file reply.
Declared at Atom because that is the erased type of the value decode_unit/1
holds on the failure path; the projection itself is total because every
:file failure arm is a 2-tuple.
fn decode_file_size(path: String, info: Tuple) -> Result(Int, FileError)
Project the size field out of a :file.read_file_info/1 reply.
Written like decode_file_type/1: the size guard runs first, then the tag
comparison, and the size field is read only in the :ok arm.
fn decode_file_type(path: String, info: Tuple) -> Result(FileType, FileError)
Project the type field out of a :file.read_file_info/1 reply.
TWO projections, in order: the reply's payload at index 2 is the
#file_info{} record, and the record's type field at index 3 is the atom
we want. Indexing the reply at 3 directly would raise badarg — the reply
is a 2-tuple, and the record is nested inside it.
fn decode_read(raw: Tuple) -> Result(Binary, FileError)
Decode a :file.read_file/1 reply into Result(Binary, FileError).
Total: the size guard runs before raw_element/2, so a malformed reply
answers Error(IoError(:bad_reply)) instead of raising badarg.
fn decode_size(info: Tuple) -> Result(Int, FileError)
Read the size field of an already-established 2-tuple reply.
TWO projections, in order: the reply's payload at index 2 is the
#file_info{} record, and the record's size field at index 2 is the byte
count. Reading the reply at index 2 directly would hand back the record
itself rather than its size.
fn decode_text(binary: Binary) -> Result(String, FileError)
Decode a UTF-8 Binary into the nominal String.
Strict by design: a file that is not valid UTF-8 answers
Error(InvalidUtf8()) rather than silently substituting replacement
characters. read_binary/1 is the escape hatch for data that is not text.
The discriminator is :erlang.is_list/1 on the untyped arm, and the
typed arm is only read once that guard has established the shape — the same
pattern decode_read/1 uses for the reply tuple.
fn decode_unit(reply: Atom) -> Result(Unit, FileError)
Decode a :file reply that either is the bare atom ok or is
{error, Reason}.
Total: the atom arm is checked first, so the tuple projection is only reached for a value that is genuinely a 2-tuple.
The two arms have genuinely different erased types (an atom vs a tuple), so
the projection is delegated to decode_error_tuple/1, whose parameter is
declared Tuple. Passing reply directly to raw_error_reason/2 would ask
the elaborator to treat an Atom-typed value as a Tuple.
fn directory?(path: String) -> Bool
true when path names an existing directory.
Examples
mod DirectoryDocExample
use Trusted.File
fn is_dir(path: String) -> Bool = directory?(path)
fn discard_staging(staging: String, reason: FileError) -> Result(Unit, FileError)
Preserve the operation's original failure even if best-effort cleanup fails.
fn drop_last(remaining: List(String), acc: List(String)) -> List(String)
Every segment except the last, preserving order.
fn entries_from_charlists(remaining: List(List(Char)), acc: List(String)) -> List(String)
Convert each charlist entry to a String, in reverse order.
Declared at List(List(Char)) — the shape :file.list_dir/1 documents for
its payload. decode_dir_listing/2 establishes that shape before this is
reached, so the list destructuring below is total.
fn exists?(path: String) -> Bool
true when path names an existing regular file.
Total by construction: the file-info reply is discriminated before any
projection, so a missing path answers false rather than raising.
Examples
mod ExistsDocExample
use Trusted.File
fn present(path: String) -> Bool = exists?(path)
fn file_type(path: String) -> Result(FileType, FileError)
The :file type of path.
Total: the reply is discriminated before projection, so a missing path
answers Error(NotFound()) rather than raising badarg.
fn finish_staged_write(path: String, staging: String, device: Atom, bytes: Binary) -> Result(Unit, FileError)
Write and close only the descriptor this invocation created. Rename is reached only after both succeeded; every failure cleans up our own sibling.
fn info_type(record: Tuple) -> Atom
Project the type field out of a #file_info{} record.
Reuses raw_element_tag/2 rather than declaring a fourth
(Int, Tuple) -> Atom binding: Cure rejects two externs with the same
callable signature, and raw_element_tag, raw_error_reason, and a
dedicated raw_info_type would all be exactly that. The record is a tuple
and type is its third field, so the existing binding is the right one.
fn insert_string(s: String, sorted: List(String)) -> List(String)
Insert s into an already-sorted list, preserving order.
fn is_absolute(path: String) -> Bool
true when path begins with a separator.
fn join_with_slash(segments: List(String), acc: String) -> String
Join segments with /, starting from acc.
fn list(path: String) -> Result(List(String), FileError)
The entries of a directory, excluding . and .., sorted.
Examples
mod ListDocExample
use Std.List
use Std.Result
use Trusted.File
fn count(path: String) -> Int =
match list(path)
Ok(entries) -> Std.List.length(entries)
Error(_) -> 0
fn mkdir_p(path: String) -> Result(Unit, FileError)
Create a directory and every missing parent.
An existing directory answers Ok(()): the post-condition is "the directory
exists", and a caller that cannot tell "created" from "already there"
cannot make mkdir_p idempotent.
Examples
mod MkdirDocExample
use Std.Result
use Trusted.File
use Trusted.Error
fn prepare(path: String) -> String =
match mkdir_p(path)
Ok(_) -> "ready"
Error(reason) -> describe(reason)
fn mkdir_parent(path: String, reason: FileError) -> Result(Unit, FileError)
Create path, falling back to creating its parent first.
Only NotFound() is retried: it means a parent is missing, which is the one
case a recursive call fixes. Any other reason is returned unchanged, so a
permission failure is not retried once per path segment.
The recursion is bounded by parent_of/1 returning a STRICTLY SHORTER path
at every step, and by the .// roots being terminal. Those two properties
are asserted in parent_of/1's documentation; without them this function
would loop forever on a path whose parent is itself.
fn open_for_append(path: String) -> Result(Atom, FileError)
Open path in raw binary append mode.
:file.open/2 answers {ok, Device} or {error, Reason} — both tuples, so
the reply is declared Tuple at the boundary and the tag at index 1 decides
which arm it is.
fn parent_of(path: String) -> String
The parent directory of path.
"a/b/c" answers "a/b"; a single-segment path answers ".". Trailing and
repeated separators are normalised away by Std.String.split_on/2, which
omits empty pieces.
Two properties make this safe to recurse on:
- An absolute path stays absolute. The leading
/is restored from the original string, so/tmp/a/banswers/tmp/arather than the relativetmp/a— which would makemkdir_pcreate the wrong tree. - The result is never the input.
"."and"/"are their own parents, so they are terminal:mkdir_pstops there instead of looping.
fn publish_staged_write(path: String, staging: String) -> Result(Unit, FileError)
Publish a closed, complete staging file. A rename failure leaves the old target intact and removes the staging file rather than leaking it.
fn raw_characters_to_chars(binary: Binary) -> List(Char)
Trust: :unicode.characters_to_list/1 for the charlist arm. Declared separately at
List(Char) so the discriminator's result can be handed to
Std.String.from_characters/1 without a cast: the guard has already
established the shape.
fn raw_characters_to_list(binary: Binary) -> Any
Trust: :unicode.characters_to_list/1 answers a charlist for valid UTF-8,
or {error, Converted, Rest} / {incomplete, Converted, Rest} for invalid
or truncated input. Declared at Any because the failure arms are tuples,
not lists; decode_text/1 discriminates with :erlang.is_list/1 before
touching the value.
fn raw_close(device: Atom) -> Atom
Trust: :file.close/1 answers ok or {error, Reason}.
fn raw_delete(path: List(Char)) -> Atom
Trust: :file.delete/1 answers ok or {error, Reason}. A missing file
answers {error, :enoent} rather than ok.
fn raw_dir_entries(index: Int, listing: Tuple) -> List(List(Char))
Trust: :erlang.element/2 on the payload position of a :file.list_dir/1
reply. Declared at List(List(Char)) — the shape OTP documents for the
payload — because the caller has already established the 2-tuple shape and
the :ok tag, so this arm is only reached for a real directory listing.
fn raw_element(index: Int, tuple: Tuple) -> Binary
Trust: :erlang.element/2 is 1-based and raises badarg when the index is
out of range. Every call below is guarded by a raw_tuple_size/1 check, so
the index is always in 1..2.
Declared at Binary because the only position this module projects is the
payload of a successful {:ok, Binary} reply. The tag at index 1 is read
through raw_element_tag/2 below, which is declared at Atom for the same
reason: the declared type is a claim about the ERASED value at that
position, and Any would make == :ok unelaboratable.
fn raw_element_tag(index: Int, tuple: Tuple) -> Atom
Trust: :erlang.element/2 as raw_element/2, but for the reply's tag position, which holds
the atom :ok or :error.
fn raw_error_reason(index: Int, reply: Tuple) -> Atom
Trust: :erlang.element/2 on the reason position of a {error, Reason}
reply. Declared at Tuple for the reply (every :file reply is a 2-tuple)
and Atom for the reason, which is what every POSIX reason is. The caller
has already established the 2-tuple shape, so the index is in range.
fn raw_error_reason_at(index: Int, reply: Atom) -> Atom
Trust: :erlang.element/2 on the reason position of a {error, Reason}
reply whose static type is the erased Atom carrier.
A second binding of the same BIF, declared at Atom for the reply, because
decode_error_tuple/1 only has the erased value in hand. The index is in
range: every :file failure arm is a 2-tuple.
fn raw_info_record(index: Int, info: Tuple) -> Tuple
Trust: :erlang.element/2 on the payload position of a
:file.read_file_info/1 reply. Declared at Tuple because the payload is
the opaque #file_info{} record, which is a tuple. The caller established
the reply's 2-tuple shape and its :ok tag, so index 2 is in range.
fn raw_is_integer(term: Atom) -> Bool
Trust: :erlang.is_integer/1 is a pure type test; it never raises.
fn raw_is_list(term: Any) -> Bool
Trust: :erlang.is_list/1 is a pure type test; it never raises.
fn raw_is_tuple(term: Atom) -> Bool
Trust: :erlang.is_tuple/1 is a pure type test; it never raises. Used to
discriminate the {error, Reason} arm of a :file reply from the ok
atom before projecting the reason.
fn raw_list_dir(path: List(Char)) -> Tuple
Trust: :file.list_dir/1 answers {ok, Filenames} or {error, Reason},
where Filenames are charlists without a directory prefix. We rely on
the 2-tuple shape and on the payload being a list.
fn raw_make_dir(path: List(Char)) -> Atom
Trust: :file.make_dir/1 answers ok or {error, Reason}. :eexist is
reported rather than swallowed, which is what lets mkdir_p/1 distinguish
"already there" from a genuine failure.
fn raw_open(path: List(Char), modes: List(Atom)) -> Tuple
Trust: :file.open/2 answers {ok, IoDevice} or {error, Reason}.
append/2 uses [:append, :raw, :binary]; atomic writes use
[:write, :exclusive, :raw, :binary]. Exclusive creation fails with
:eexist rather than opening any existing file or following its symlink.
The device speaks raw binaries rather than going through the io protocol.
Declared at Tuple: both arms are 2-tuples.
fn raw_read_file(path: List(Char)) -> Tuple
Trust: :file.read_file/1 answers {ok, Binary} on success or
{error, Reason} on failure, where Reason is a POSIX atom.
OTP kernel reference, file module. We rely on: (a) the 2-tuple shape,
(b) Reason being an atom.
fn raw_read_file_info(path: List(Char)) -> Tuple
Trust: :file.read_file_info/1 answers {ok, FileInfo} or
{error, Reason}, where FileInfo is an opaque #file_info{} record.
We rely on: the 2-tuple shape and the record's field order, which OTP
documents as stable (size at position 2, type at position 3).
Declared at Tuple — the success arm's shape — because a caller that
projects the record has already established it. The failure arm is a
2-tuple too, so every reply from this function IS a tuple; the tag at
index 1 is what distinguishes them.
fn raw_rename(from: List(Char), to: List(Char)) -> Atom
Trust: :file.rename/2 answers ok or {error, Reason}. Rename within a
directory is atomic on every POSIX filesystem, which is what makes
write/2 all-or-nothing.
fn raw_size_field(index: Int, record: Tuple) -> Int
Read the size field out of a #file_info{} record.
Total: the field is documented as an integer, but it is checked anyway --
a :file reply that is not the documented shape answers
Error(IoError(:bad_reply)) instead of handing the caller a non-integer.
Trust: :erlang.element/2 on the size field of a #file_info{} record.
OTP documents the record's field order as stable, with size at position 2
and an integer value.
fn raw_tuple_size(tuple: Tuple) -> Int
Trust: :erlang.tuple_size/1 raises badarg on a non-tuple. Only ever
called on a value :file.read_file/1 produced, which is always a tuple.
fn raw_unique_integer(options: List(Atom)) -> Int
Trust: :erlang.unique_integer/1 with [:positive, :monotonic] returns
a positive integer unique within this VM. It is NOT globally unique:
exclusive file creation, not this suffix, establishes staging ownership
across VMs. Collisions are retried with a bounded budget.
fn raw_write(device: Atom, bytes: Binary) -> Atom
Trust: :file.write/2 on a raw device answers ok or {error, Reason}.
fn read(path: String) -> Result(String, FileError)
Read a whole file as UTF-8 text.
Answers Error(InvalidUtf8()) when the bytes are not valid UTF-8; use
read_binary/1 for data that is not text.
Examples
mod ReadDocExample
use Std.Result
use Trusted.File
use Trusted.Error
fn contents(path: String) -> String =
match read(path)
Ok(text) -> text
Error(NotFound()) -> ""
Error(_) -> ""
fn read_binary(path: String) -> Result(Binary, FileError)
Read a whole file as raw bytes, with no decoding.
The escape hatch for binary data and for text in an encoding other than
UTF-8. Pair it with Std.Binary to inspect or convert the bytes.
Examples
mod ReadBinaryDocExample
use Std.Binary
use Std.Result
use Trusted.File
fn size_of(path: String) -> Int =
match read_binary(path)
Ok(bytes) -> Std.Binary.byte_size(bytes)
Error(_) -> 0
fn remove(path: String) -> Result(Unit, FileError)
Delete a file.
A missing file answers Error(NotFound()) rather than succeeding silently:
"delete what is not there" is a caller mistake, and hiding it makes a
cleanup routine that never ran look like one that did.
Examples
mod RemoveDocExample
use Std.Result
use Trusted.File
use Trusted.Error
fn cleanup(path: String) -> String =
match remove(path)
Ok(_) -> "removed"
Error(NotFound()) -> "was not there"
Error(_) -> "failed"
fn reverse_strings(remaining: List(String), acc: List(String)) -> List(String)
Reverse a list of strings.
fn size(path: String) -> Result(Int, FileError)
File size in bytes.
Examples
mod SizeDocExample
use Std.Result
use Trusted.File
fn bytes(path: String) -> Int =
match size(path)
Ok(n) -> n
Error(_) -> 0
fn sort_strings(remaining: List(String), acc: List(String)) -> List(String)
Insertion sort over String, using Std.String's Comparable instance.
Insertion sort rather than Std.List.sort because the latter needs a
Comparable dictionary threaded at the call site; the entry lists here are
directory listings, so the quadratic term is immaterial.
fn stage_write(path: String, bytes: Binary, attempts: Int) -> Result(Unit, FileError)
Try at most attempts exclusive sibling names. A failed open does not
confer ownership, so its path must never be cleaned up.
fn terminal_path(path: String) -> Bool
true when path is a filesystem root that cannot have a parent.
These are the recursion's base cases. mkdir_p(".") and mkdir_p("/")
answer Error(NotFound()) rather than recursing, because there is nothing
above them to create.
fn try_staging(path: String, staging: String, bytes: Binary, attempts: Int) -> Result(Unit, FileError)
Attempt one exclusive open. Keep collision handling separate from naming: an existing file or symlink belongs to someone else, even on the last try.
fn write(path: String, text: String) -> Result(Unit, FileError)
Write text to path, replacing it atomically.
Exclusively creates a unique sibling, writes and closes its descriptor, then renames it into place. Concurrent writers never share a staging inode, and existing staging entries are never opened, truncated, or deleted. Readers observe a complete old or new file on filesystems with atomic same-directory rename. This is atomic visibility, not power-loss durability: there is no file or directory sync. Replacement uses the newly created file's permissions (subject to the process umask), not the old file's mode. The containing directory must not be modified by an adversarial process.
Examples
mod WriteDocExample
use Std.Result
use Trusted.File
use Trusted.Error
fn save(path: String, text: String) -> String =
match write(path, text)
Ok(_) -> "written"
Error(reason) -> describe(reason)
fn write_and_close(device: Atom, bytes: Binary) -> Result(Unit, FileError)
Write bytes to device, then close it.
The device is closed on both paths: a write failure must not leak the file descriptor, and the close result is only reported when the write succeeded (a close error after a successful write is still a failure, but a write error is the more informative one).
fn write_binary(path: String, bytes: Binary) -> Result(Unit, FileError)
Write raw bytes to path, replacing it atomically.
The byte-level twin of write/2, for data that is not text.
Examples
mod WriteBinaryDocExample
use Std.Binary
use Std.Result
use Trusted.File
fn save(path: String) -> String =
match write_binary(path, Std.Binary.of_bytes([1, 2, 3]))
Ok(_) -> "written"
Error(_) -> "failed"