day-spec 0.6.2

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! Bundled resources: efficient random read-only access to app-declared data, backed by each
//! toolkit's native resource mechanism (DESIGN.md §18.3).
//!
//! `day build` stages the files declared under a project's `assets/` (and `images/`) into each
//! platform's native resource store, **uncompressed where possible** so the runtime can hand back a
//! zero-copy view. At runtime `resource("name")` returns a [`Resource`] whose bytes are borrowed
//! directly from that store: an mmap of a bundle file on Apple, the NDK `AAssetManager` buffer on
//! Android, `g_resources_lookup_data` on GTK, `QResource::data` on Qt, the rawfile fd on ArkUI.
//!
//! The active backend registers its opener once via [`set_resource_opener`]; if none is registered
//! (desktop dev, host tests, and the Apple backends, whose native mechanism *is* a bundle file) the
//! default opener mmaps the file resolved from `DAY_ASSET_ROOT` or the app bundle.

use std::any::Any;
use std::borrow::Cow;
use std::path::PathBuf;
use std::sync::OnceLock;

// ---------------------------------------------------------------------------
// Typed resource identifiers (§18.5)
//
// `image(...)`, `resource(...)`, and `Font::custom(...)` take these newtypes rather than a bare
// `&str`. Every value is meant to come from a generated `res::images/assets/fonts::…` constant
// (`day-build`), so referencing a resource that isn't bundled is a compile error and the available
// names autocomplete. A string *literal* does not coerce, which is what turns "present" from a
// convention into a guarantee; a name only known at runtime uses the explicit `::dynamic`
// escape hatch (or, for images/assets, `From<String>`).
// ---------------------------------------------------------------------------

macro_rules! resource_name {
    ($(#[$m:meta])* $name:ident, $what:literal) => {
        $(#[$m])*
        #[derive(Clone, Debug, PartialEq, Eq)]
        pub struct $name(Cow<'static, str>);

        impl $name {
            #[doc = concat!("A ", $what, " known at compile time — the form the generated `res::…` constants use.")]
            pub const fn from_static(name: &'static str) -> Self {
                $name(Cow::Borrowed(name))
            }
            #[doc = concat!("Escape hatch for a ", $what, " computed at runtime (no build-time presence guarantee).")]
            pub fn dynamic(name: impl Into<String>) -> Self {
                $name(Cow::Owned(name.into()))
            }
            /// The underlying wire name the backend resolves by.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        // Owned strings convert (dynamic names); a `&str` literal does not, so
        // `image("typo")` / `resource("typo")` fail to compile.
        impl From<String> for $name {
            fn from(s: String) -> Self {
                $name(Cow::Owned(s))
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(&self.0)
            }
        }
    };
}

resource_name!(
    /// The bundled-image name that [`resource()`](crate::resource()) callers resolve by (the file stem).
    ImageName,
    "bundled-image name"
);
resource_name!(
    /// The bundled-data name that [`resource`] resolves by: the file's path relative to
    /// `resource/assets/`, `/`-separated (a top-level file is just its file name, extension
    /// included).
    AssetName,
    "bundled-asset name"
);
resource_name!(
    /// A bundled-asset directory (§18.5): a folder's path relative to `resource/assets/`,
    /// `/`-separated, no trailing slash. The generated `res::assets::…` tree carries one
    /// constant per folder, sharing its module's name: `res::assets::web::minisite` is the
    /// `AssetDir` and `res::assets::web::minisite::index_html` a file within it.
    AssetDir,
    "bundled-asset directory"
);

impl AssetDir {
    /// Name a file under this directory, for [`resource`]: the escape hatch for paths
    /// composed at runtime (`dir.join("posts/1.html")`); prefer the generated file constants
    /// where the path is known.
    pub fn join(&self, rel: &str) -> AssetName {
        AssetName::dynamic(format!("{}/{}", self.as_str(), rel.trim_start_matches('/')))
    }
}
resource_name!(
    /// The bundled-vector name that [`resource()`](crate::resource()) callers resolve by (docs/vectors.md):
    /// the stem of a `resource/vectors/` SVG (or `.symbolset` bundle). Vectors and images share one
    /// per-backend resolution namespace; staging guarantees every vector name resolves as whatever
    /// form that backend loads natively (a VectorDrawable, a catalog entry, a rasterized PNG).
    VectorName,
    "bundled-vector name"
);

/// Vector and image names resolve through the same per-backend channel (nav-item icons, the
/// toolbar's `.image(…)`, `bar_action`, all name-based); this conversion is that shared
/// namespace made explicit.
impl From<VectorName> for ImageName {
    fn from(v: VectorName) -> ImageName {
        ImageName::dynamic(v.as_str().to_owned())
    }
}

/// The family name of a bundled custom font, feeding `Font::custom`. Holds a `&'static str` (so
/// `Font` stays `Copy`); generated `res::fonts::…` constants supply it. The untyped
/// `Font::Custom(&'static str, f64)` variant remains the escape hatch for a family known another way.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FontFamily(&'static str);

impl FontFamily {
    /// A font family known at compile time: the form the generated `res::fonts::…` constants use.
    pub const fn from_static(family: &'static str) -> Self {
        FontFamily(family)
    }
    /// The underlying family name (what `Font::Custom` carries).
    pub const fn as_str(&self) -> &'static str {
        self.0
    }
}

impl std::fmt::Display for FontFamily {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0)
    }
}

/// A handle to a bundled resource's bytes with efficient random read-only access.
///
/// The bytes stay valid for the lifetime of the `Resource`: it owns a guard (an mmap, a native
/// `GBytes`/`QResource`/`AAsset` handle, or an owned buffer) that keeps the backing store alive.
/// `Resource` is neither `Send` nor `Sync`; like the rest of the day runtime it is used on the
/// main/UI thread.
pub struct Resource {
    ptr: *const u8,
    len: usize,
    /// Keeps the backing store alive while `ptr`/`len` are borrowed from it.
    _guard: Box<dyn Any>,
}

impl Resource {
    /// Build a `Resource` from a raw byte view plus the guard that owns it. Backends call this from
    /// their opener after obtaining a zero-copy pointer from the native resource API.
    ///
    /// # Safety
    /// `ptr` must point to `len` valid, immutable bytes that remain valid for as long as `guard` is
    /// alive, and `guard` must own (and keep alive) that backing store.
    pub unsafe fn from_raw(ptr: *const u8, len: usize, guard: Box<dyn Any>) -> Resource {
        Resource {
            ptr,
            len,
            _guard: guard,
        }
    }

    /// Build a `Resource` from owned bytes: the copy fallback for backends that cannot expose a
    /// stable pointer into their store (or when a native API only offers a read-into-buffer call).
    pub fn from_vec(bytes: Vec<u8>) -> Resource {
        let boxed: Box<[u8]> = bytes.into_boxed_slice();
        let ptr = boxed.as_ptr();
        let len = boxed.len();
        // Moving the box moves the (fat) pointer, not the heap allocation, so `ptr` stays valid.
        Resource {
            ptr,
            len,
            _guard: Box::new(boxed),
        }
    }

    /// Total byte length of the resource.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Whether the resource is empty.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// A zero-copy view of the full contents. Backed directly by the native store (no allocation,
    /// no copy). Wrap in [`std::io::Cursor`] for `Read`/`Seek`-style access.
    pub fn as_slice(&self) -> &[u8] {
        // Safety: `ptr`/`len` describe a valid immutable region kept alive by `_guard`.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }

    /// Random-access read: copy up to `buf.len()` bytes starting at `offset` into `buf`, returning
    /// the number of bytes copied (0 if `offset >= len`). A direct `memcpy` from the backing store,
    /// no allocation: the efficient primitive for seeking around a large embedded blob.
    pub fn read_at(&self, offset: usize, buf: &mut [u8]) -> usize {
        let data = self.as_slice();
        if offset >= data.len() {
            return 0;
        }
        let n = buf.len().min(data.len() - offset);
        buf[..n].copy_from_slice(&data[offset..offset + n]);
        n
    }

    /// Copy the full contents into a freshly allocated `Vec`.
    pub fn to_vec(&self) -> Vec<u8> {
        self.as_slice().to_vec()
    }
}

/// A backend's resource opener: maps a declared name (e.g. `"stations.json"`) to its bytes, or
/// `None` if there is no such resource.
pub type ResourceOpener = fn(&str) -> Option<Resource>;

static OPENER: OnceLock<ResourceOpener> = OnceLock::new();

/// Register the active backend's resource opener (Android `AAssetManager`, GTK `GResource`, Qt
/// `QResource`, ArkUI rawfile, …). Called once during backend init. A second call is ignored, so a
/// backend that shares the default file opener need not call this at all.
pub fn set_resource_opener(opener: ResourceOpener) {
    let _ = OPENER.set(opener);
}

/// Open a bundled resource by name for efficient random read-only access.
///
/// Returns `None` if the backend has no resource with that name. Takes an [`AssetName`]: pass a
/// generated `res::assets::…` constant (e.g. `resource(res::assets::stations_json)`) for a checked,
/// guaranteed-present reference, or [`AssetName::dynamic`] for a name known only at runtime.
pub fn resource(name: impl Into<AssetName>) -> Option<Resource> {
    let name = name.into();
    let name = name.as_str();
    match OPENER.get() {
        Some(open) => open(name),
        None => default_open(name),
    }
}

/// The default opener: mmap the file resolved from `DAY_ASSET_ROOT` (dev runs / `day launch`) or the
/// app bundle's `Resources/assets`. This is the Apple backends' native path (a plain bundle file)
/// and the desktop/host-test path.
fn default_open(name: &str) -> Option<Resource> {
    let path = resolve_resource_path(name)?;
    let file = std::fs::File::open(&path).ok()?;
    // Safety: we open read-only and never mutate the mapping; the `Mmap` guard keeps it alive.
    let mmap = unsafe { memmap2::Mmap::map(&file).ok()? };
    let ptr = mmap.as_ptr();
    let len = mmap.len();
    Some(unsafe { Resource::from_raw(ptr, len, Box::new(mmap)) })
}

/// Resolve a data-resource name to an on-disk path: `DAY_ASSET_ROOT` first (dev / CLI launch), then
/// bundle-relative locations next to the executable (macOS `.app`, Linux `share`).
fn resolve_resource_path(name: &str) -> Option<PathBuf> {
    for var in ASSET_ROOT_VARS {
        if let Ok(root) = std::env::var(var) {
            let p = PathBuf::from(root).join(name);
            if p.exists() {
                return Some(p);
            }
        }
    }
    if let Ok(exe) = std::env::current_exe()
        && let Some(dir) = exe.parent()
    {
        for rel in ["../Resources/assets", "Resources/assets", "assets"] {
            let p = dir.join(rel).join(name);
            if p.exists() {
                return Some(p);
            }
        }
    }
    None
}

/// Resolve a data-asset file (a `/`-relative path under `resource/assets/`) to its on-disk
/// location, for consumers that must hand a native API a path rather than bytes: lottie-ios
/// takes a filepath, and its by-name initializer would otherwise look only at the bundle root,
/// where Day stages nothing. Same probe order as [`resource`]: `DAY_ASSET_ROOT` (dev /
/// `day launch`), then the bundle-relative roots.
/// The roots a dev run probes for data assets, in order: the project's own `resource/assets/`,
/// then the tree `day build` stages the assets its pieces ship into (docs/extending.md). A
/// packaged app has one merged `assets/` directory beside the binary and needs neither.
const ASSET_ROOT_VARS: [&str; 2] = ["DAY_ASSET_ROOT", "DAY_PIECE_ASSET_ROOT"];

pub fn resolve_asset_file(name: &str) -> Option<PathBuf> {
    resolve_resource_path(name)
}

/// Resolve a data-asset directory (an [`AssetDir`]'s `/`-relative path) to its on-disk
/// location, for consumers whose local-content channel is a file URL, like the inline web
/// view on the Apple backends (day-piece-webview's docs/webview.md). Same probe order as file
/// resolution: `DAY_ASSET_ROOT` (dev / `day launch`), then the bundle-relative roots.
pub fn resolve_asset_dir(rel: &str) -> Option<PathBuf> {
    // Canonicalized: consumers derive URLs from this path, and a literal `..` segment (the
    // bundle probe below goes through `MacOS/../Resources`) breaks prefix comparison against
    // the standardized URLs engines report back.
    let canon = |p: PathBuf| p.canonicalize().ok().filter(|c| c.is_dir());
    for var in ASSET_ROOT_VARS {
        if let Ok(root) = std::env::var(var)
            && let Some(p) = canon(PathBuf::from(root).join(rel))
        {
            return Some(p);
        }
    }
    if let Ok(exe) = std::env::current_exe()
        && let Some(dir) = exe.parent()
    {
        for base in ["../Resources/assets", "Resources/assets", "assets"] {
            if let Some(p) = canon(dir.join(base).join(rel)) {
                return Some(p);
            }
        }
    }
    None
}

/// Image file extensions probed when an `image("name")` reference omits an extension.
const IMAGE_EXTS: [&str; 8] = ["png", "jpg", "jpeg", "gif", "bmp", "webp", "pdf", "svg"];

/// The suffixes `Vector::weight` appends to a glyph name (docs/vectors.md).
pub const WEIGHT_SUFFIXES: [&str; 2] = ["__light", "__bold"];

/// The base glyph a weight-suffixed name aliases, or `None` if the name carries no suffix.
///
/// Only SF-template sources have true per-weight art, so only they stage `__light`/`__bold`
/// assets. A plain SVG stages once and every weight resolves back to it here, which is what
/// keeps `.weight(…)` from 404-ing on art that has no weight axis, without staging a byte-identical
/// copy of every glyph per weight. (Before this, 38 of Day-Showcase's 39 sources were staged three
/// times over as identical copies.)
pub fn weight_alias(name: &str) -> Option<&str> {
    WEIGHT_SUFFIXES
        .iter()
        .find_map(|s| name.strip_suffix(s))
        .filter(|base| !base.is_empty())
}

/// Resolve an image name to an on-disk file, for the file-loading backends (AppKit/GTK/Qt, and the
/// desktop/dev path). Probes `DAY_IMAGE_ROOT` (the project's `images/` under `day launch`) first,
/// then `DAY_ASSET_ROOT` and the bundle, trying the bare name and, if it has no extension, each
/// known image extension. Native-pipeline backends (iOS `Assets.car`, Android `R`, …) resolve by
/// name through their own store and do not use this.
pub fn resolve_image_file(name: &str) -> Option<PathBuf> {
    let mut roots: Vec<PathBuf> = Vec::new();
    // DAY_VECTOR_RASTER_ROOT: the build-time raster cache for `resource/vectors/`
    // (docs/vectors.md), which is how the file-loading desktop backends resolve a vector name
    // with no native vector pipeline.
    for var in ["DAY_IMAGE_ROOT", "DAY_VECTOR_RASTER_ROOT", "DAY_ASSET_ROOT"] {
        if let Ok(v) = std::env::var(var) {
            roots.push(PathBuf::from(v));
        }
    }
    if let Ok(exe) = std::env::current_exe()
        && let Some(dir) = exe.parent()
    {
        // Packed layouts (docs/vectors.md): `day pack` stages the vector raster cache under
        // `vectors/raster` (inside `Contents/Resources` for a .app, beside the exe for the
        // flat Windows payload), ordered after `images` to mirror the env-root precedence.
        for rel in [
            "../Resources/images",
            "../Resources/vectors/raster",
            "../Resources/assets",
            "images",
            "vectors/raster",
            "assets",
        ] {
            roots.push(dir.join(rel));
        }
    }
    // A weight-suffixed name probes its own art first, then the base glyph it aliases
    // (`weight_alias`): the raster half of the same fallback the SVG resolver does.
    let names: Vec<&str> = match weight_alias(name) {
        Some(base) => vec![name, base],
        None => vec![name],
    };
    let has_ext = std::path::Path::new(name).extension().is_some();
    // Name-major, not root-major: a staged variant found in any root beats the base glyph found in
    // a higher-precedence one, so a template's own `__bold` art is never shadowed by its Regular.
    for (name, root) in names
        .iter()
        .flat_map(|n| roots.iter().map(move |r| (*n, r.clone())))
    {
        let exact = root.join(name);
        if exact.is_file() {
            return Some(exact);
        }
        if !has_ext {
            for ext in IMAGE_EXTS {
                let p = root.join(format!("{name}.{ext}"));
                if p.is_file() {
                    return Some(p);
                }
            }
        }
    }
    None
}

/// Resolve a vector name to its staged glyph SVG, for backends that render SVG natively
/// (docs/vectors.md): `DAY_VECTOR_SVG_ROOT` under `day launch`, else the packed layouts:
/// `Contents/Resources/vectors/svg` in a .app, `vectors/svg` beside a flat-layout exe.
/// `None` (name isn't a vector, or the layout carries no SVGs) means fall back to
/// [`resolve_image_file`]'s raster resolution.
pub fn resolve_vector_svg(name: &str) -> Option<PathBuf> {
    let mut roots: Vec<PathBuf> = Vec::new();
    if let Ok(v) = std::env::var("DAY_VECTOR_SVG_ROOT") {
        roots.push(PathBuf::from(v));
    }
    if let Ok(exe) = std::env::current_exe()
        && let Some(dir) = exe.parent()
    {
        roots.push(dir.join("../Resources/vectors/svg"));
        roots.push(dir.join("vectors/svg"));
    }
    if let Some(found) = roots
        .iter()
        .map(|r| r.join(format!("{name}.svg")))
        .find(|p| p.is_file())
    {
        return Some(found);
    }
    // A weight that stages no art of its own resolves to the base glyph (see `weight_alias`).
    let base = weight_alias(name)?;
    roots
        .into_iter()
        .map(|r| r.join(format!("{base}.svg")))
        .find(|p| p.is_file())
}

/// Resolve a vector name to its staged XAML geometry (docs/vectors.md), the form day-toolkit-winui draws
/// as real `Path` geometry: vector at any size, and tintable by brush at runtime.
/// `DAY_VECTOR_XAML_ROOT` under `day launch`, else `vectors/xaml` beside a flat-layout exe.
/// `None` (name isn't a vector, the art was outside the convertible subset, or the layout
/// carries no geometry) means fall back to [`resolve_image_file`]'s raster resolution.
pub fn resolve_vector_xaml(name: &str) -> Option<PathBuf> {
    let mut roots: Vec<PathBuf> = Vec::new();
    if let Ok(v) = std::env::var("DAY_VECTOR_XAML_ROOT") {
        roots.push(PathBuf::from(v));
    }
    if let Ok(exe) = std::env::current_exe()
        && let Some(dir) = exe.parent()
    {
        roots.push(dir.join("vectors/xaml"));
    }
    if let Some(found) = roots
        .iter()
        .map(|r| r.join(format!("{name}.xamlgeom")))
        .find(|p| p.is_file())
    {
        return Some(found);
    }
    let base = weight_alias(name)?;
    roots
        .into_iter()
        .map(|r| r.join(format!("{base}.xamlgeom")))
        .find(|p| p.is_file())
}

/// Day's own drawing of `sym`, written to a cache file and answered as a path.
///
/// Backends that load icons from files (Qt's SVG icon engine, gdk-pixbuf) can then use the shared
/// fallback through the loader they already have, instead of each growing a way to rasterize a
/// path string. Written once per symbol per process; a failure to write answers `None` and the
/// caller falls back to a label.
pub fn stage_symbol_svg(sym: crate::Symbol) -> Option<PathBuf> {
    let svg = sym.outline_svg()?;
    let dir = std::env::temp_dir().join("day-symbols");
    let file = dir.join(format!("{sym:?}.svg"));
    if file.is_file() {
        return Some(file);
    }
    std::fs::create_dir_all(&dir).ok()?;
    std::fs::write(&file, svg).ok()?;
    Some(file)
}

#[cfg(test)]
mod tests {
    use super::*;

    // One test owns the process env (set_var races across threads), covering both the default
    // data opener and the image-file resolver sequentially.
    #[test]
    fn env_backed_resource_access() {
        let dir = std::env::temp_dir().join(format!("day-res-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let payload: Vec<u8> = (0u8..=255).cycle().take(1000).collect();
        std::fs::write(dir.join("blob.bin"), &payload).unwrap();
        std::fs::write(dir.join("logo.png"), b"x").unwrap();
        // SAFETY: this is the only test that touches the env.
        unsafe {
            std::env::set_var("DAY_ASSET_ROOT", &dir);
            std::env::set_var("DAY_IMAGE_ROOT", &dir);
        }

        // default data opener: whole view + random access + clamping + miss.
        let res = resource(AssetName::from_static("blob.bin")).expect("resource present");
        assert_eq!(res.len(), 1000);
        assert!(!res.is_empty());
        assert_eq!(res.as_slice(), &payload[..]);
        let mut buf = [0u8; 16];
        assert_eq!(res.read_at(500, &mut buf), 16);
        assert_eq!(&buf, &payload[500..516]);
        assert_eq!(res.read_at(995, &mut buf), 5);
        assert_eq!(&buf[..5], &payload[995..1000]);
        assert_eq!(res.read_at(2000, &mut buf), 0);
        assert!(resource(AssetName::from_static("does-not-exist.bin")).is_none());
        // Dynamic names go through the explicit escape hatch.
        assert!(resource(AssetName::dynamic(String::from("nope.bin"))).is_none());

        // image-file resolver: extension inference + exact + miss.
        assert_eq!(resolve_image_file("logo"), Some(dir.join("logo.png")));
        assert_eq!(resolve_image_file("logo.png"), Some(dir.join("logo.png")));
        assert_eq!(resolve_image_file("missing"), None);

        // Weight aliasing (docs/vectors.md): a plain SVG stages one asset, so its `__light` /
        // `__bold` names must resolve back to it rather than miss. `logo` has no weight art of
        // its own, which is exactly the case every non-template glyph is in.
        assert_eq!(weight_alias("logo__bold"), Some("logo"));
        assert_eq!(weight_alias("logo"), None);
        assert_eq!(weight_alias("__bold"), None); // suffix alone aliases nothing
        assert_eq!(resolve_image_file("logo__bold"), Some(dir.join("logo.png")));
        assert_eq!(
            resolve_image_file("logo__light"),
            Some(dir.join("logo.png"))
        );
        // A miss stays a miss: the alias must not invent art for a name with no base either.
        assert_eq!(resolve_image_file("missing__bold"), None);

        // The SVG resolver aliases the same way, and a staged variant still wins over its base.
        let svgs = dir.join("svg");
        std::fs::create_dir_all(&svgs).unwrap();
        std::fs::write(svgs.join("plain.svg"), b"<svg/>").unwrap();
        std::fs::write(svgs.join("tmpl.svg"), b"<svg/>").unwrap();
        std::fs::write(svgs.join("tmpl__bold.svg"), b"<svg/>").unwrap();
        // SAFETY: single test owning the env.
        unsafe { std::env::set_var("DAY_VECTOR_SVG_ROOT", &svgs) };
        assert_eq!(
            resolve_vector_svg("plain__bold"),
            Some(svgs.join("plain.svg"))
        );
        assert_eq!(
            resolve_vector_svg("tmpl__bold"),
            Some(svgs.join("tmpl__bold.svg")),
            "a staged variant must not be shadowed by its base"
        );
        assert_eq!(resolve_vector_svg("absent__bold"), None);
        // SAFETY: single test owning the env.
        unsafe { std::env::remove_var("DAY_VECTOR_SVG_ROOT") };

        // SAFETY: single test owning the env.
        unsafe {
            std::env::remove_var("DAY_ASSET_ROOT");
            std::env::remove_var("DAY_IMAGE_ROOT");
        }
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn from_vec_view_is_stable() {
        let r = Resource::from_vec(vec![1, 2, 3, 4]);
        assert_eq!(r.as_slice(), &[1, 2, 3, 4]);
        assert_eq!(r.to_vec(), vec![1, 2, 3, 4]);
        let mut b = [0u8; 2];
        assert_eq!(r.read_at(2, &mut b), 2);
        assert_eq!(b, [3, 4]);
    }
}