59 lines
2.8 KiB
Plaintext
59 lines
2.8 KiB
Plaintext
;;;; Assets baked in at compile time — NEXT.md decision 1.
|
|
;;;;
|
|
;;;; Odin's #load and #load_directory are the model, spelled as ordinary named
|
|
;;;; calls because an s-expression language already has a head position and
|
|
;;;; does not need Odin's `#`. The whole reason for preferring this to a build
|
|
;;;; flag is that it is a *compiler* feature: no linker arguments, no
|
|
;;;; per-target packaging, and identical on desktop and web. A single-file
|
|
;;;; program has no link channel at all — `Load` hands out lflags only to a
|
|
;;;; directory package — so the file that needs the asset is structurally the
|
|
;;;; one file that could not declare it. Embedding has no such hole.
|
|
;;;;
|
|
;;;; Nothing here costs anything at run time: every one of these is a
|
|
;;;; `private unnamed_addr constant` in the emitted module.
|
|
|
|
;; Bound once at top level, where it becomes an LLVM constant outright rather
|
|
;; than an array rebuilt on the stack per call (emit.ml's `const`).
|
|
(defconst assets [3 EmbedFile] (embed-dir "assets"))
|
|
|
|
(defn main [] i32
|
|
;; The default answer is a [u8]: bytes, because that is what an asset is.
|
|
(let [a (embed "assets/a.txt")]
|
|
(println (len a)) ; 13
|
|
(print (string a))) ; hello from a
|
|
|
|
;; `string` is the second spelling, not a different meaning for the same
|
|
;; text. With structural equality and nothing that converts one container
|
|
;; into another -- implicit widening is numbers only -- one form that changes
|
|
;; type with its context would be a wart.
|
|
(println (embed "assets/b.bin" string)) ; BBB
|
|
|
|
;; Byte-exact, including bytes no text encoding would survive: emit.ml's
|
|
;; escape hex-escapes everything outside printable ASCII, so a PNG makes the
|
|
;; round trip through the .ll unchanged.
|
|
(let [raw (embed "assets/raw.bin")]
|
|
(println (len raw)) ; 4
|
|
(println (at raw 0)) ; 0
|
|
(println (at raw 2)) ; 255
|
|
(println (at raw 3))) ; 254
|
|
|
|
;; A directory embed is a fixed array of EmbedFile, sorted by name — sorted
|
|
;; because readdir order is filesystem-dependent and an unsorted embed would
|
|
;; make two builds of identical sources emit different .ll.
|
|
(println (len assets)) ; 3
|
|
(println (.name (at assets 0))) ; a.txt
|
|
(println (.name (at assets 1))) ; b.bin
|
|
(println (.name (at assets 2))) ; raw.bin
|
|
|
|
;; The name-to-bytes lookup is a linear scan in the prelude. It takes a slice
|
|
;; rather than the array, because an array's length is part of its type and
|
|
;; there are no generics.
|
|
(let [all (slice assets 0 (len assets))]
|
|
(match (embed-find all "b.bin")
|
|
(Some b) (println (string b)) ; BBB
|
|
None (println "missing"))
|
|
(match (embed-find all "nope.txt")
|
|
(Some _) (println "found")
|
|
None (println "no nope.txt"))) ; no nope.txt
|
|
0)
|