std/resource/resource
std/resource/src/resource.trb
Resource, EmbeddedBytes and EmbeddedText: the three types a string literal names a file of the package with
(docs/design/RESOURCES.md section 4). They are capsules over the stable name the compiler resolved - the owner and
name of the package, then the path inside it, always with / - so the only way to make one is a literal.
type Resource
type Resource with Show, Equals, Hash
A file that ships with the program and is read while it runs, found relative to the program and never to the
working directory. A literal where a Resource is expected names a file of the package, relative to the file that
writes it; torb build copies it to <program>.resources/<stable name> beside the binary, and bytes() and
text() read it from there.
Examples
fn load(sheet: Resource): String {
sheet.name()
}
fn readme(file: Resource): Task<Result<String, ResourceError>> {
file.text().await()
}
Errors
ResourceErrorfrombytes()andtext(): not shipped, unreadable, not UTF-8, or the program's location unknown.
Pitfalls
- A path is compared byte for byte on every platform:
./Hero.pngnext tohero.pngis an error on Windows too. - A
Stringvalue is never a resource: a path chosen while the program runs is aPath, read throughstd/fs. - A binary that is moved needs its
<program>.resourcesdirectory beside it; without it every read is anErr(NotShipped).
fn name
fn name(): String
What the file is called: acme/game/src/sheets/hero.spr, the text a diagnostic and a log print.
fn bytes
fn bytes(): Task<Result<Bytes, ResourceError>>
The bytes of the file, read from the resource directory of the running program - <program>.resources/ beside
its executable, never the working directory. The Task is complete when it is returned on a native target.
Errors
ResourceError.NotShippedwhere the file is not in that directory, such as a binary moved without it.ResourceError.Unreadablewhere the file is there and cannot be read.ResourceError.Unlocatedwhere the program cannot tell where its executable is.
fn text
fn text(): Task<Result<String, ResourceError>>
The file as text. Bytes that are not UTF-8 are a ResourceError.NotUtf8 with the offset of the first bad byte, and
never a replacement character. Its other errors are those of bytes().
fn show
fn show(): String
The stable name, the same text as name().
type EmbeddedBytes
type EmbeddedBytes with Show, Equals, Hash
A file whose bytes are in the binary. Reading them cannot fail: the compiler has the file in its hands.
type EmbeddedText
type EmbeddedText with Show, Equals, Hash
A file whose text is in the binary, so reading it cannot fail: the compiler reads the file, and checks its UTF-8, where the literal names it (slice 2 of docs/design/RESOURCES.md).