Skip to main content

day_spec/
resource.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Bundled resources: efficient random read-only access to app-declared data, backed by each
5//! toolkit's native resource mechanism (DESIGN.md §18.3).
6//!
7//! `day build` stages the files declared under a project's `assets/` (and `images/`) into each
8//! platform's native resource store, **uncompressed where possible** so the runtime can hand back a
9//! zero-copy view. At runtime `resource("name")` returns a [`Resource`] whose bytes are borrowed
10//! directly from that store: an mmap of a bundle file on Apple, the NDK `AAssetManager` buffer on
11//! Android, `g_resources_lookup_data` on GTK, `QResource::data` on Qt, the rawfile fd on ArkUI.
12//!
13//! The active backend registers its opener once via [`set_resource_opener`]; if none is registered
14//! (desktop dev, host tests, and the Apple backends, whose native mechanism *is* a bundle file) the
15//! default opener mmaps the file resolved from `DAY_ASSET_ROOT` or the app bundle.
16
17use std::any::Any;
18use std::borrow::Cow;
19use std::path::PathBuf;
20use std::sync::OnceLock;
21
22// ---------------------------------------------------------------------------
23// Typed resource identifiers (§18.5)
24//
25// `image(...)`, `resource(...)`, and `Font::custom(...)` take these newtypes rather than a bare
26// `&str`. Every value is meant to come from a generated `res::images/assets/fonts::…` constant
27// (`day-build`), so referencing a resource that isn't bundled is a compile error and the available
28// names autocomplete. A string *literal* does not coerce, which is what turns "present" from a
29// convention into a guarantee; a name only known at runtime uses the explicit `::dynamic`
30// escape hatch (or, for images/assets, `From<String>`).
31// ---------------------------------------------------------------------------
32
33macro_rules! resource_name {
34    ($(#[$m:meta])* $name:ident, $what:literal) => {
35        $(#[$m])*
36        #[derive(Clone, Debug, PartialEq, Eq)]
37        pub struct $name(Cow<'static, str>);
38
39        impl $name {
40            #[doc = concat!("A ", $what, " known at compile time — the form the generated `res::…` constants use.")]
41            pub const fn from_static(name: &'static str) -> Self {
42                $name(Cow::Borrowed(name))
43            }
44            #[doc = concat!("Escape hatch for a ", $what, " computed at runtime (no build-time presence guarantee).")]
45            pub fn dynamic(name: impl Into<String>) -> Self {
46                $name(Cow::Owned(name.into()))
47            }
48            /// The underlying wire name the backend resolves by.
49            pub fn as_str(&self) -> &str {
50                &self.0
51            }
52        }
53
54        // Owned strings convert (dynamic names); a `&str` literal does not, so
55        // `image("typo")` / `resource("typo")` fail to compile.
56        impl From<String> for $name {
57            fn from(s: String) -> Self {
58                $name(Cow::Owned(s))
59            }
60        }
61
62        impl std::fmt::Display for $name {
63            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64                f.write_str(&self.0)
65            }
66        }
67    };
68}
69
70resource_name!(
71    /// The bundled-image name that [`resource()`](crate::resource()) callers resolve by (the file stem).
72    ImageName,
73    "bundled-image name"
74);
75resource_name!(
76    /// The bundled-data name that [`resource`] resolves by: the file's path relative to
77    /// `resource/assets/`, `/`-separated (a top-level file is just its file name, extension
78    /// included).
79    AssetName,
80    "bundled-asset name"
81);
82resource_name!(
83    /// A bundled-asset directory (§18.5): a folder's path relative to `resource/assets/`,
84    /// `/`-separated, no trailing slash. The generated `res::assets::…` tree carries one
85    /// constant per folder, sharing its module's name: `res::assets::web::minisite` is the
86    /// `AssetDir` and `res::assets::web::minisite::index_html` a file within it.
87    AssetDir,
88    "bundled-asset directory"
89);
90
91impl AssetDir {
92    /// Name a file under this directory, for [`resource`]: the escape hatch for paths
93    /// composed at runtime (`dir.join("posts/1.html")`); prefer the generated file constants
94    /// where the path is known.
95    #[must_use]
96    pub fn join(&self, rel: &str) -> AssetName {
97        AssetName::dynamic(format!("{}/{}", self.as_str(), rel.trim_start_matches('/')))
98    }
99}
100resource_name!(
101    /// The bundled-vector name that [`resource()`](crate::resource()) callers resolve by (docs/vectors.md):
102    /// the stem of a `resource/vectors/` SVG (or `.symbolset` bundle). Vectors and images share one
103    /// per-backend resolution namespace; staging guarantees every vector name resolves as whatever
104    /// form that backend loads natively (a `VectorDrawable`, a catalog entry, a rasterized PNG).
105    VectorName,
106    "bundled-vector name"
107);
108
109/// Vector and image names resolve through the same per-backend channel (nav-item icons, the
110/// toolbar's `.image(…)`, `bar_action`, all name-based); this conversion is that shared
111/// namespace made explicit.
112impl From<VectorName> for ImageName {
113    fn from(v: VectorName) -> ImageName {
114        ImageName::dynamic(v.as_str().to_owned())
115    }
116}
117
118/// The family name of a bundled custom font, feeding `Font::custom`. Holds a `&'static str` (so
119/// `Font` stays `Copy`); generated `res::fonts::…` constants supply it. The untyped
120/// `Font::Custom(&'static str, f64)` variant remains the escape hatch for a family known another way.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122pub struct FontFamily(&'static str);
123
124impl FontFamily {
125    /// A font family known at compile time: the form the generated `res::fonts::…` constants use.
126    #[must_use]
127    pub const fn from_static(family: &'static str) -> Self {
128        FontFamily(family)
129    }
130    /// The underlying family name (what `Font::Custom` carries).
131    #[must_use]
132    pub const fn as_str(&self) -> &'static str {
133        self.0
134    }
135}
136
137impl std::fmt::Display for FontFamily {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        f.write_str(self.0)
140    }
141}
142
143/// A handle to a bundled resource's bytes with efficient random read-only access.
144///
145/// The bytes stay valid for the lifetime of the `Resource`: it owns a guard (an mmap, a native
146/// `GBytes`/`QResource`/`AAsset` handle, or an owned buffer) that keeps the backing store alive.
147/// `Resource` is neither `Send` nor `Sync`; like the rest of the day runtime it is used on the
148/// main/UI thread.
149pub struct Resource {
150    ptr: *const u8,
151    len: usize,
152    /// Keeps the backing store alive while `ptr`/`len` are borrowed from it.
153    _guard: Option<Box<dyn Any>>,
154}
155
156impl Resource {
157    /// Borrow immutable bytes embedded in the executable, without allocating or copying.
158    #[must_use]
159    pub fn from_static(bytes: &'static [u8]) -> Resource {
160        Resource {
161            ptr: bytes.as_ptr(),
162            len: bytes.len(),
163            _guard: None,
164        }
165    }
166
167    /// Build a `Resource` from a raw byte view plus the guard that owns it. Backends call this from
168    /// their opener after obtaining a zero-copy pointer from the native resource API.
169    ///
170    /// # Safety
171    /// `ptr` must point to `len` valid, immutable bytes that remain valid for as long as `guard` is
172    /// alive, and `guard` must own (and keep alive) that backing store.
173    #[must_use]
174    pub unsafe fn from_raw(ptr: *const u8, len: usize, guard: Box<dyn Any>) -> Resource {
175        Resource {
176            ptr,
177            len,
178            _guard: Some(guard),
179        }
180    }
181
182    /// Build a `Resource` from owned bytes: the copy fallback for backends that cannot expose a
183    /// stable pointer into their store (or when a native API only offers a read-into-buffer call).
184    #[must_use]
185    pub fn from_vec(bytes: Vec<u8>) -> Resource {
186        let boxed: Box<[u8]> = bytes.into_boxed_slice();
187        let ptr = boxed.as_ptr();
188        let len = boxed.len();
189        // Moving the box moves the (fat) pointer, not the heap allocation, so `ptr` stays valid.
190        Resource {
191            ptr,
192            len,
193            _guard: Some(Box::new(boxed)),
194        }
195    }
196
197    /// Total byte length of the resource.
198    #[must_use]
199    pub fn len(&self) -> usize {
200        self.len
201    }
202
203    /// Whether the resource is empty.
204    #[must_use]
205    pub fn is_empty(&self) -> bool {
206        self.len == 0
207    }
208
209    /// A zero-copy view of the full contents. Backed directly by the native store (no allocation,
210    /// no copy). Wrap in [`std::io::Cursor`] for `Read`/`Seek`-style access.
211    #[must_use]
212    pub fn as_slice(&self) -> &[u8] {
213        // Safety: `ptr`/`len` describe a valid immutable region kept alive by `_guard`.
214        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
215    }
216
217    /// Random-access read: copy up to `buf.len()` bytes starting at `offset` into `buf`, returning
218    /// the number of bytes copied (0 if `offset >= len`). A direct `memcpy` from the backing store,
219    /// no allocation: the efficient primitive for seeking around a large embedded blob.
220    pub fn read_at(&self, offset: usize, buf: &mut [u8]) -> usize {
221        let data = self.as_slice();
222        if offset >= data.len() {
223            return 0;
224        }
225        let n = buf.len().min(data.len() - offset);
226        buf[..n].copy_from_slice(&data[offset..offset + n]);
227        n
228    }
229
230    /// Copy the full contents into a freshly allocated `Vec`.
231    #[must_use]
232    pub fn to_vec(&self) -> Vec<u8> {
233        self.as_slice().to_vec()
234    }
235}
236
237/// A backend's resource opener: maps a declared name (e.g. `"stations.json"`) to its bytes, or
238/// `None` if there is no such resource.
239pub type ResourceOpener = fn(&str) -> Option<Resource>;
240
241static OPENER: OnceLock<ResourceOpener> = OnceLock::new();
242
243/// Register the active backend's resource opener (Android `AAssetManager`, GTK `GResource`, Qt
244/// `QResource`, ArkUI rawfile, …). Called once during backend init. A second call is ignored, so a
245/// backend that shares the default file opener need not call this at all.
246pub fn set_resource_opener(opener: ResourceOpener) {
247    let _ = OPENER.set(opener);
248}
249
250/// Open a bundled resource by name for efficient random read-only access.
251///
252/// Returns `None` if the backend has no resource with that name. Takes an [`AssetName`]: pass a
253/// generated `res::assets::…` constant (e.g. `resource(res::assets::stations_json)`) for a checked,
254/// guaranteed-present reference, or [`AssetName::dynamic`] for a name known only at runtime.
255pub fn resource(name: impl Into<AssetName>) -> Option<Resource> {
256    let name = name.into();
257    let name = name.as_str();
258    match OPENER.get() {
259        Some(open) => open(name),
260        None => default_open(name),
261    }
262}
263
264/// The default opener: mmap the file resolved from `DAY_ASSET_ROOT` (dev runs / `day launch`) or the
265/// app bundle's `Resources/assets`. This is the Apple backends' native path (a plain bundle file)
266/// and the desktop/host-test path.
267fn default_open(name: &str) -> Option<Resource> {
268    let path = resolve_resource_path(name)?;
269    let file = std::fs::File::open(&path).ok()?;
270    // Safety: we open read-only and never mutate the mapping; the `Mmap` guard keeps it alive.
271    let mmap = unsafe { memmap2::Mmap::map(&file).ok()? };
272    let ptr = mmap.as_ptr();
273    let len = mmap.len();
274    Some(unsafe { Resource::from_raw(ptr, len, Box::new(mmap)) })
275}
276
277/// Resolve a data-resource name to an on-disk path: `DAY_ASSET_ROOT` first (dev / CLI launch), then
278/// bundle-relative locations next to the executable (macOS `.app`, Linux `share`).
279fn resolve_resource_path(name: &str) -> Option<PathBuf> {
280    for var in ASSET_ROOT_VARS {
281        if let Ok(root) = std::env::var(var) {
282            let p = PathBuf::from(root).join(name);
283            if p.exists() {
284                return Some(p);
285            }
286        }
287    }
288    if let Ok(exe) = std::env::current_exe()
289        && let Some(dir) = exe.parent()
290    {
291        for rel in ["../Resources/assets", "Resources/assets", "assets"] {
292            let p = dir.join(rel).join(name);
293            if p.exists() {
294                return Some(p);
295            }
296        }
297    }
298    None
299}
300
301/// Resolve a data-asset file (a `/`-relative path under `resource/assets/`) to its on-disk
302/// location, for consumers that must hand a native API a path rather than bytes: lottie-ios
303/// takes a filepath, and its by-name initializer would otherwise look only at the bundle root,
304/// where Day stages nothing. Same probe order as [`resource`]: `DAY_ASSET_ROOT` (dev /
305/// `day launch`), then the bundle-relative roots.
306/// The roots a dev run probes for data assets, in order: the project's own `resource/assets/`,
307/// then the tree `day build` stages the assets its pieces ship into (docs/extending.md). A
308/// packaged app has one merged `assets/` directory beside the binary and needs neither.
309const ASSET_ROOT_VARS: [&str; 2] = ["DAY_ASSET_ROOT", "DAY_PIECE_ASSET_ROOT"];
310
311#[must_use]
312pub fn resolve_asset_file(name: &str) -> Option<PathBuf> {
313    resolve_resource_path(name)
314}
315
316/// Resolve a data-asset directory (an [`AssetDir`]'s `/`-relative path) to its on-disk
317/// location, for consumers whose local-content channel is a file URL, like the inline web
318/// view on the Apple backends (day-piece-webview's docs/webview.md). Same probe order as file
319/// resolution: `DAY_ASSET_ROOT` (dev / `day launch`), then the bundle-relative roots.
320#[must_use]
321pub fn resolve_asset_dir(rel: &str) -> Option<PathBuf> {
322    // Canonicalized: consumers derive URLs from this path, and a literal `..` segment (the
323    // bundle probe below goes through `MacOS/../Resources`) breaks prefix comparison against
324    // the standardized URLs engines report back.
325    let canon = |p: PathBuf| p.canonicalize().ok().filter(|c| c.is_dir());
326    for var in ASSET_ROOT_VARS {
327        if let Ok(root) = std::env::var(var)
328            && let Some(p) = canon(PathBuf::from(root).join(rel))
329        {
330            return Some(p);
331        }
332    }
333    if let Ok(exe) = std::env::current_exe()
334        && let Some(dir) = exe.parent()
335    {
336        for base in ["../Resources/assets", "Resources/assets", "assets"] {
337            if let Some(p) = canon(dir.join(base).join(rel)) {
338                return Some(p);
339            }
340        }
341    }
342    None
343}
344
345/// Image file extensions probed when an `image("name")` reference omits an extension.
346const IMAGE_EXTS: [&str; 8] = ["png", "jpg", "jpeg", "gif", "bmp", "webp", "pdf", "svg"];
347
348/// The suffixes `Vector::weight` appends to a glyph name (docs/vectors.md).
349pub const WEIGHT_SUFFIXES: [&str; 2] = ["__light", "__bold"];
350
351/// The base glyph a weight-suffixed name aliases, or `None` if the name carries no suffix.
352///
353/// Only SF-template sources have true per-weight art, so only they stage `__light`/`__bold`
354/// assets. A plain SVG stages once and every weight resolves back to it here, which is what
355/// keeps `.weight(…)` from 404-ing on art that has no weight axis, without staging a byte-identical
356/// copy of every glyph per weight. (Before this, 38 of Day-Showcase's 39 sources were staged three
357/// times over as identical copies.)
358#[must_use]
359pub fn weight_alias(name: &str) -> Option<&str> {
360    WEIGHT_SUFFIXES
361        .iter()
362        .find_map(|s| name.strip_suffix(s))
363        .filter(|base| !base.is_empty())
364}
365
366/// Resolve an image name to an on-disk file, for the file-loading backends (AppKit/GTK/Qt, and the
367/// desktop/dev path). Probes `DAY_IMAGE_ROOT` (the project's `images/` under `day launch`) first,
368/// then `DAY_ASSET_ROOT` and the bundle, trying the bare name and, if it has no extension, each
369/// known image extension. Native-pipeline backends (iOS `Assets.car`, Android `R`, …) resolve by
370/// name through their own store and do not use this.
371#[must_use]
372pub fn resolve_image_file(name: &str) -> Option<PathBuf> {
373    let mut roots: Vec<PathBuf> = Vec::new();
374    // DAY_VECTOR_RASTER_ROOT: the build-time raster cache for `resource/vectors/`
375    // (docs/vectors.md), which is how the file-loading desktop backends resolve a vector name
376    // with no native vector pipeline.
377    for var in ["DAY_IMAGE_ROOT", "DAY_VECTOR_RASTER_ROOT", "DAY_ASSET_ROOT"] {
378        if let Ok(v) = std::env::var(var) {
379            roots.push(PathBuf::from(v));
380        }
381    }
382    if let Ok(exe) = std::env::current_exe()
383        && let Some(dir) = exe.parent()
384    {
385        // Packed layouts (docs/vectors.md): `day pack` stages the vector raster cache under
386        // `vectors/raster` (inside `Contents/Resources` for a .app, beside the exe for the
387        // flat Windows payload), ordered after `images` to mirror the env-root precedence.
388        for rel in [
389            "../Resources/images",
390            "../Resources/vectors/raster",
391            "../Resources/assets",
392            "images",
393            "vectors/raster",
394            "assets",
395        ] {
396            roots.push(dir.join(rel));
397        }
398    }
399    // A weight-suffixed name probes its own art first, then the base glyph it aliases
400    // (`weight_alias`): the raster half of the same fallback the SVG resolver does.
401    let names: Vec<&str> = match weight_alias(name) {
402        Some(base) => vec![name, base],
403        None => vec![name],
404    };
405    let has_ext = std::path::Path::new(name).extension().is_some();
406    // Name-major, not root-major: a staged variant found in any root beats the base glyph found in
407    // a higher-precedence one, so a template's own `__bold` art is never shadowed by its Regular.
408    for (name, root) in names
409        .iter()
410        .flat_map(|n| roots.iter().map(move |r| (*n, r.clone())))
411    {
412        let exact = root.join(name);
413        if exact.is_file() {
414            return Some(exact);
415        }
416        if !has_ext {
417            for ext in IMAGE_EXTS {
418                let p = root.join(format!("{name}.{ext}"));
419                if p.is_file() {
420                    return Some(p);
421                }
422            }
423        }
424    }
425    None
426}
427
428/// Resolve a vector name to its staged glyph SVG, for backends that render SVG natively
429/// (docs/vectors.md): `DAY_VECTOR_SVG_ROOT` under `day launch`, else the packed layouts:
430/// `Contents/Resources/vectors/svg` in a .app, `vectors/svg` beside a flat-layout exe.
431/// `None` (name isn't a vector, or the layout carries no SVGs) means fall back to
432/// [`resolve_image_file`]'s raster resolution.
433#[must_use]
434pub fn resolve_vector_svg(name: &str) -> Option<PathBuf> {
435    let mut roots: Vec<PathBuf> = Vec::new();
436    if let Ok(v) = std::env::var("DAY_VECTOR_SVG_ROOT") {
437        roots.push(PathBuf::from(v));
438    }
439    if let Ok(exe) = std::env::current_exe()
440        && let Some(dir) = exe.parent()
441    {
442        roots.push(dir.join("../Resources/vectors/svg"));
443        roots.push(dir.join("vectors/svg"));
444    }
445    if let Some(found) = roots
446        .iter()
447        .map(|r| r.join(format!("{name}.svg")))
448        .find(|p| p.is_file())
449    {
450        return Some(found);
451    }
452    // A weight that stages no art of its own resolves to the base glyph (see `weight_alias`).
453    let base = weight_alias(name)?;
454    roots
455        .into_iter()
456        .map(|r| r.join(format!("{base}.svg")))
457        .find(|p| p.is_file())
458}
459
460/// Resolve a vector name to its staged XAML geometry (docs/vectors.md), the form day-toolkit-winui draws
461/// as real `Path` geometry: vector at any size, and tintable by brush at runtime.
462/// `DAY_VECTOR_XAML_ROOT` under `day launch`, else `vectors/xaml` beside a flat-layout exe.
463/// `None` (name isn't a vector, the art was outside the convertible subset, or the layout
464/// carries no geometry) means fall back to [`resolve_image_file`]'s raster resolution.
465#[must_use]
466pub fn resolve_vector_xaml(name: &str) -> Option<PathBuf> {
467    let mut roots: Vec<PathBuf> = Vec::new();
468    if let Ok(v) = std::env::var("DAY_VECTOR_XAML_ROOT") {
469        roots.push(PathBuf::from(v));
470    }
471    if let Ok(exe) = std::env::current_exe()
472        && let Some(dir) = exe.parent()
473    {
474        roots.push(dir.join("vectors/xaml"));
475    }
476    if let Some(found) = roots
477        .iter()
478        .map(|r| r.join(format!("{name}.xamlgeom")))
479        .find(|p| p.is_file())
480    {
481        return Some(found);
482    }
483    let base = weight_alias(name)?;
484    roots
485        .into_iter()
486        .map(|r| r.join(format!("{base}.xamlgeom")))
487        .find(|p| p.is_file())
488}
489
490/// Day's own drawing of `sym`, written to a cache file and answered as a path.
491///
492/// Backends that load icons from files (Qt's SVG icon engine, gdk-pixbuf) can then use the shared
493/// fallback through the loader they already have, instead of each growing a way to rasterize a
494/// path string. Written once per symbol per process; a failure to write answers `None` and the
495/// caller falls back to a label.
496#[must_use]
497pub fn stage_symbol_svg(sym: crate::Symbol) -> Option<PathBuf> {
498    let svg = sym.outline_svg()?;
499    let dir = std::env::temp_dir().join("day-symbols");
500    let file = dir.join(format!("{sym:?}.svg"));
501    if file.is_file() {
502        return Some(file);
503    }
504    std::fs::create_dir_all(&dir).ok()?;
505    std::fs::write(&file, svg).ok()?;
506    Some(file)
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512
513    // One test owns the process env (set_var races across threads), covering both the default
514    // data opener and the image-file resolver sequentially.
515    #[test]
516    fn env_backed_resource_access() {
517        let dir = std::env::temp_dir().join(format!("day-res-test-{}", std::process::id()));
518        std::fs::create_dir_all(&dir).unwrap();
519        let payload: Vec<u8> = (0u8..=255).cycle().take(1000).collect();
520        std::fs::write(dir.join("blob.bin"), &payload).unwrap();
521        std::fs::write(dir.join("logo.png"), b"x").unwrap();
522        // SAFETY: this is the only test that touches the env.
523        unsafe {
524            std::env::set_var("DAY_ASSET_ROOT", &dir);
525            std::env::set_var("DAY_IMAGE_ROOT", &dir);
526        }
527
528        // default data opener: whole view + random access + clamping + miss.
529        let res = resource(AssetName::from_static("blob.bin")).expect("resource present");
530        assert_eq!(res.len(), 1000);
531        assert!(!res.is_empty());
532        assert_eq!(res.as_slice(), &payload[..]);
533        let mut buf = [0u8; 16];
534        assert_eq!(res.read_at(500, &mut buf), 16);
535        assert_eq!(&buf, &payload[500..516]);
536        assert_eq!(res.read_at(995, &mut buf), 5);
537        assert_eq!(&buf[..5], &payload[995..1000]);
538        assert_eq!(res.read_at(2000, &mut buf), 0);
539        assert!(resource(AssetName::from_static("does-not-exist.bin")).is_none());
540        // Dynamic names go through the explicit escape hatch.
541        assert!(resource(AssetName::dynamic(String::from("nope.bin"))).is_none());
542
543        // image-file resolver: extension inference + exact + miss.
544        assert_eq!(resolve_image_file("logo"), Some(dir.join("logo.png")));
545        assert_eq!(resolve_image_file("logo.png"), Some(dir.join("logo.png")));
546        assert_eq!(resolve_image_file("missing"), None);
547
548        // Weight aliasing (docs/vectors.md): a plain SVG stages one asset, so its `__light` /
549        // `__bold` names must resolve back to it rather than miss. `logo` has no weight art of
550        // its own, which is exactly the case every non-template glyph is in.
551        assert_eq!(weight_alias("logo__bold"), Some("logo"));
552        assert_eq!(weight_alias("logo"), None);
553        assert_eq!(weight_alias("__bold"), None); // suffix alone aliases nothing
554        assert_eq!(resolve_image_file("logo__bold"), Some(dir.join("logo.png")));
555        assert_eq!(
556            resolve_image_file("logo__light"),
557            Some(dir.join("logo.png"))
558        );
559        // A miss stays a miss: the alias must not invent art for a name with no base either.
560        assert_eq!(resolve_image_file("missing__bold"), None);
561
562        // The SVG resolver aliases the same way, and a staged variant still wins over its base.
563        let svgs = dir.join("svg");
564        std::fs::create_dir_all(&svgs).unwrap();
565        std::fs::write(svgs.join("plain.svg"), b"<svg/>").unwrap();
566        std::fs::write(svgs.join("tmpl.svg"), b"<svg/>").unwrap();
567        std::fs::write(svgs.join("tmpl__bold.svg"), b"<svg/>").unwrap();
568        // SAFETY: single test owning the env.
569        unsafe { std::env::set_var("DAY_VECTOR_SVG_ROOT", &svgs) };
570        assert_eq!(
571            resolve_vector_svg("plain__bold"),
572            Some(svgs.join("plain.svg"))
573        );
574        assert_eq!(
575            resolve_vector_svg("tmpl__bold"),
576            Some(svgs.join("tmpl__bold.svg")),
577            "a staged variant must not be shadowed by its base"
578        );
579        assert_eq!(resolve_vector_svg("absent__bold"), None);
580        // SAFETY: single test owning the env.
581        unsafe { std::env::remove_var("DAY_VECTOR_SVG_ROOT") };
582
583        // SAFETY: single test owning the env.
584        unsafe {
585            std::env::remove_var("DAY_ASSET_ROOT");
586            std::env::remove_var("DAY_IMAGE_ROOT");
587        }
588        std::fs::remove_dir_all(&dir).ok();
589    }
590
591    #[test]
592    fn from_vec_view_is_stable() {
593        let r = Resource::from_vec(vec![1, 2, 3, 4]);
594        assert_eq!(r.as_slice(), &[1, 2, 3, 4]);
595        assert_eq!(r.to_vec(), vec![1, 2, 3, 4]);
596        let mut b = [0u8; 2];
597        assert_eq!(r.read_at(2, &mut b), 2);
598        assert_eq!(b, [3, 4]);
599    }
600}
601
602#[cfg(test)]
603mod embedded_tests {
604    use super::Resource;
605    #[test]
606    fn static_resources_borrow_and_read_without_copying() {
607        static BYTES: &[u8] = &[10, 20, 30, 40];
608        let a = Resource::from_static(BYTES);
609        let b = Resource::from_static(BYTES);
610        assert_eq!(a.as_slice().as_ptr(), BYTES.as_ptr());
611        assert_eq!(b.as_slice().as_ptr(), a.as_slice().as_ptr());
612        let mut out = [0; 4];
613        assert_eq!(a.read_at(2, &mut out), 2);
614        assert_eq!(out, [30, 40, 0, 0]);
615        assert_eq!(a.read_at(usize::MAX, &mut out), 0);
616        assert!(Resource::from_static(&[]).is_empty());
617    }
618}